An event listener is added once my video starts playing. That is

document.getElementById("myVideo").addEventListener("timeUpdate", myFunction);

and then just before the video ends I want something to happen (perhaps a fade out) along with the last few seconds of the video (or to keep things simple I'm just going to write something like alert("goodbye");) instead.

and when I use this piece of code

 var myVideo = document.getElementById ("myVideo");
 function myFunction(){
   if(myVideo.currentTime >= (myVideo.duration-3) )
   {
     alert("this goodbye message is supposed to be displayed only once and exactly three seconds before the video ends");
     myVideo.removeEventListener("timeupdate", myFunction);
   }
  }

it works in Chrome but it's unstable. Sometimes it works fine but other times the alert keeps popping a few times before the event listener is actually removed (which is bad in my case). In Firefox it is even worse as it fires many times. I know that different browsers make timeupdate event fire at very different intervals.

So what do you think? Should I give up on the addEventListener() removeEventListener() couple and use setInterval()clearInterval() to check where the playhead is and do stuff when the time comes. That way instead of browser dependent time intervals I could set my own time interval for consistency. But does anybody know if there is a reliable way to do this with timeUpdate?

1 Answers

0
Community On

I used a timer instead and now it works perfectly.

var checkThePlayheadPositionTenTimesASecond = setInterval(myTimer, 100);
function myTimer()
      {
        if(myVideo.currentTime >= (myVideo.duration-3) )
           {
             alert("this video is going to end in three seconds");
             clearInterval(checkThePlayheadPositionTenTimesASecond);
           }
      }

Still I'm going to leave this post active in case anyone has to say anything.