Most accurate video pause on Earth (currentTime Vs mediaTime And requestVideoFrameCallback Vs setInterval)

Let’s say we want to try our best to create the most accurate video pause function based on the given point (of time) of the video element.

So we try this to experiment:

var vid = document.getElementById("myVideo");

Method1();
Method2();

function Method1() {
  const doSomethingWithTheFrame = (now, metadata) => {
  // Do something with the frame.
  console.log(vid.currentTime, now, metadata);
  if(metadata.mediaTime >= 0.5) {
    console.log("Method1 Executed Here", vid.currentTime, metadata.mediaTime);
    vid.pause(); // reached 0.5 so stop the video
    return;
  }
  // Re-register the callback to be notified about the next frame.
  vid.requestVideoFrameCallback(doSomethingWithTheFrame);
};
  // Initially register the callback to be notified about the first frame.
  vid.requestVideoFrameCallback(doSomethingWithTheFrame);
}

function Method2() {
  const endCheck = setInterval(endCheckInterval, 5);
  function endCheckInterval() {
    if (vid.currentTime >= 0.5) {
       clearInterval(endCheck);
       console.log("Method2 Executed Here", vid.currentTime);
       //vid.pause(); // reached 0.5 so stop the video
 
    }
  }
}
<!DOCTYPE html> 
<html> 
<body> 
  <video id="myVideo" width="320" height="176" controls>
    <source src="https://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
  </video>
</body> 
</html>

As you see I compared vid.currentTime Vs metadata.mediaTime and there is a little difference between the two…

Which one should we use for reliability and accurate pausing at the 0.5 second of the video?

Answer

In Chromium’s implementation, we use the audio clock as the time source that backs video.currentTime, whereas the mediaTime is directly populated by the presentationTimestamp of the frame. The mediaTime is what you should use if you want to exactly identify frames in a reproducible way, including to identify exactly which frames you missed.