I'm trying to keep track of the time while using window.requestAnimationFrame() but the += operator keeps returning NaN even though the value I'm incrementing by isn't NaN
var elapsedTime = 0
var lastTime = 0
var between = 500
var count = 0
var betweenCount = 0
function frame(time) {
elapsedTime = time - lastTime
console.log(elapsedTime)
lastTime = time
betweenCount += elapsedTime
console.log(betweenCount)
window.requestAnimationFrame(frame)
}
frame()
betweenCount should be keeping track of the total elapsed time since its last reset, but it becomes NaN as soon as elapsedTime is assigned to it, but elapsed time isn't NaN at that point.
Since you're calling frame()
without any arguments the first time, time
will be undefined
in the function, elapsedTime
will become undefined - lastTime
which is NaN
.
You need to give the initial frame()
call a valid argument, e.g. 0
.