I am trying to add secondsPassed to timePassed but when doing so I get NaN.
I can’t find anything wrong so why is timePassed = NaN when adding secondsPassed to it?
JavaScript
x
40
40
1
var secondsPassed = 0;
2
var oldTimeStamp = 0;
3
let fps;
4
var posX = 0, posY = 0;
5
var timePassed = 0.0;
6
7
setTimeout(gameLoop, 100);
8
9
function gameLoop(timeStamp){
10
11
//seconds since last frame
12
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
13
oldTimeStamp = timeStamp;
14
15
// Move forward in time with a maximum amount
16
secondsPassed = Math.min(secondsPassed, 0.1);
17
18
//calculate fps
19
fps = Math.round(1 / secondsPassed);
20
21
//run game functions
22
update(secondsPassed);
23
24
25
//loop again
26
window.requestAnimationFrame(gameLoop);
27
}
28
29
function update(secondsPassed){
30
31
console.log(secondsPassed);
32
timePassed += secondsPassed;
33
console.log(timePassed);
34
35
36
37
posX = 200 * timePassed;
38
posY = 400;
39
40
}
Advertisement
Answer
You don’t seem to pass timeStamp
argument to gameLoop()
function. Passing it fixes the issue. Also make sure, your oldTimeStamp
is initialized.
+new Date()
is a way to create a timestamp from Date
object.
JavaScript
1
39
39
1
let secondsPassed;
2
let oldTimeStamp = +new Date() - (60*5);
3
let fps;
4
let frame;
5
let posX = 0, posY = 0;
6
let timePassed = 0;
7
8
setTimeout(gameLoop(+new Date()), 1000);
9
10
function update(secondsPassed){
11
console.log("sec: " + secondsPassed);
12
timePassed += secondsPassed;
13
console.log("time: " + timePassed);
14
15
posX = 200 * timePassed;
16
posY = 400;
17
18
}
19
20
function gameLoop(timeStamp){
21
22
//seconds since last frame
23
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
24
oldTimeStamp = timeStamp;
25
26
// Move forward in time with a maximum amount
27
secondsPassed = Math.min(secondsPassed, 0.1);
28
29
//calculate fps
30
fps = Math.round(1 / secondsPassed);
31
frame++;
32
33
update(secondsPassed);
34
//draw();
35
//run game functions
36
37
//loop again
38
window.requestAnimationFrame(gameLoop);
39
}