Search code examples
javascriptrequestanimationframe

requestAnimationFrame inital timestamp


How do you get the inital timestamp for delta calculations in a requestAnimationFrame loop?

Here ive read that

It's [requestAnimationFrame(timestamp)] a DOMHighResTimeStamp or a high-resolution timestamp (the same you get with window.performance.now())

thus I tried to do the following:

let lastTimestamp = performance.now()
const loop = (timestamp) => {
  console.log("exec at " + timestamp + " with delta " + (timestamp - lastTimestamp))

  lastTimestamp = timestamp
  requestAnimationFrame(loop)
}

requestAnimationFrame(loop)

But this gives negative values at the first frame sometimes. Which I really want to aviod since that might corrupt Animation logic. Id also like to not go with cheeky solutions inside the continuesly called loop (like if (firstFrame) // do something differntly) for performance reasons.


Solution

  • Just set the variable to null to start. First time it runs it will be null. Check for it.

    var loops = 0
    
    let lastTimestamp = null
    const loop = (timestamp) => {
      if (!lastTimestamp) {
        console.log("First Time!");
      } else {
        console.log("exec at " + timestamp + " with delta " + (timestamp - lastTimestamp))    
      }
      lastTimestamp = timestamp
      loops++
      if (loops<10) {  // just so demo is not runaway loop
        requestAnimationFrame(loop)
      }
    }
    
    requestAnimationFrame(loop)