FootsieNG
FootsieNG

Reputation: 819

HTML5 video - detected when current time equals a certain value

I am trying to detect when the current time of a html video equals a particular value, but I think I am going about it the wrong way.

JS to load video source (works fine)

document.querySelector("#videoBox > source").src =  $scope.videoUrl;
var video = document.getElementById("videoBox");

JS to detect current time

if (video.currentTime == 0.2){
    alert("Time reached!");
   }

If I check the currentTime==0 it is correctly detected before the video starts, however it doesn't work for other durations. Would appreciate any help.

Upvotes: 2

Views: 3331

Answers (1)

Marko
Marko

Reputation: 461

When the document is loaded the if statement is checked once and not again. So if you check for video.currentTime == 0 is true but for video.currentTime == 0.2 is false, try something like this:

var interval = setInterval(checkTime, 100);
function checkTime(){
if(Math.floor(video.currentTime) == 2){
  alert("Time reached!");
  clearInterval(interval);
}
}

In this way you will check for the time every 100 miliseconds and if time is 0.2 the interval is stoped

Upvotes: 4

Related Questions