javascriptdomperformance.now

performance.now and document.timeline.currentTime


MDN performance.now():

The performance.now() method returns a high resolution timestamp in milliseconds. It represents the time elapsed since Performance.timeOrigin

MDN document.timeline.currentTime

This timeline expresses the time in milliseconds since Performance.timeOrigin.

Web Animations:

Furthermore, since the time values of the default document timeline have a zero offset from the time origin, document.timeline.currentTime will roughly correspond to Performance.now()

console.log(performance.now(), document.timeline.currentTime)

has the different values. Why?


Solution

  • Because the timeline's currentTime is only updated when the Web Animations are, which is in the update the rendering steps of the event-loop.

    So if you keep requesting currentTime during a loop, you'll get only one value:

    const timestamps = new Set();
    const t1 = performance.now();
    while (performance.now() - t1 < 3000) { // perform below code for 3s
      timestamps.add(document.timeline.currentTime);
    }
    console.log([...timestamps]); // a single value

    Note that this timestamp should be the same as the one passed to requestAnimationFrame callbacks in a Window context though:

    let i = 0;
    const anim = (timestamp) => {
      console.log('same timestamps', timestamp === document.timeline.currentTime);
      if (i++ < 10)
        requestAnimationFrame(anim);
    }
    requestAnimationFrame(anim);