Sara Ree
Sara Ree

Reputation: 3543

Check when the video reached the end of it

I want to check when the movie has reached to the very end of it. As we know when the video is finished it pauses. I want to check right this moment:

So I tried to get the total duration of the video and check if the video current time is more than that point:

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

checkTime();


async function checkTime() {

  const durationOfMovie = await getDuration(); 
  console.log("durationOfMovie", durationOfMovie);
  
  const doSomethingWithTheFrame = (now, metadata) => {
    console.log("metadata.mediaTime", metadata.mediaTime);
    // We want to check this to detect the movie reached the End
    if(metadata.mediaTime >= durationOfMovie) {
        console.log("Movie Reached The End");
        return;
    }
    vid.requestVideoFrameCallback(doSomethingWithTheFrame);
    };
  // Initially register the callback to be notified about the first frame.
  vid.requestVideoFrameCallback(doSomethingWithTheFrame);
}

function getDuration() {
  return new Promise((resolve) => {        
    vid.addEventListener("durationchange", checkDuration);
    function checkDuration() {
      if(this.duration !== Infinity) {
        vid.removeEventListener("durationchange", checkDuration);
        const duration = this.duration;
        return resolve(duration);
      }
    }
    vid.load();
    vid.currentTime = 3000; // fake time
  });
}
<!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>

But As you see the durationOfMovie is always more than what metadata.mediaTime could show so we could never check the end of the video!!!

Why this is not working?

For different videos the difference between durationOfMovie and metadata.mediaTime is different and that makes more confusion...

Upvotes: 0

Views: 691

Answers (1)

Ben West
Ben West

Reputation: 4596

There's an ended event: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/ended_event

vid.addEventListener('ended', () => console.log("it's over"));

Upvotes: 1

Related Questions