0

I have written this code in HTML5 video to play around with the time functionality. If I set this line of code as

if(vid.currentTime > 5){
        vid.pause();
     }

the video will automatically pause, which is what i want. But if I set it as

if(vid.currentTime == 5){
        vid.pause();
     }

it refuses to pause and I want it to pause at different times in order to fire different actions. I don't know why. I have researched and tried to google similar situation but no luck. Any help will be appreciated. Here is the full code:

window.onload = init;

let vid;

function init() {


    vid = document.querySelector("#myPlayer");

    vid.ontimeupdate = displayTimeWhileVideoIsPlaying;
}

function playVideo() {
    vid.play();
}

function pauseVideo() {
    vid.pause();
}

function rewindVideo() {
    vid.currentTime = 0
}

function displayTimeWhileVideoIsPlaying(evt) {
    console.log(vid.currentTime);
    ccc = 5;
    if(vid.currentTime > 5){
        vid.pause();
     }

}

This is the link to my codepen for a working demo: https://codepen.io/Okezie/pen/xWOLQd?editors=1011
The issue is presumably on line 28 of my code pen.

kahveci
  • 1,429
  • 9
  • 23

1 Answers1

3

You could keep track of which pause points were hit , and not pause again.

var points = [ 
    { time: 5 , done: false},
      { time: 6 , done: false},
    { time: 8 , done: false},
    { time: 9 , done: false},
];

function displayTimeWhileVideoIsPlaying(evt) {

for(var point of points){
  console.log(vid.currentTime);
  if(vid.currentTime > point.time){
      if(!point.done){
        vid.pause();
        //vid.currentTime = point.time; //Optional, if you want to pause exact
        point.done = true;
      }
   }
}

The !point.done check guards against the 'inexactness' of the greater than check. It prevents the pause from taking effect at 5.3, 5.4, 5.8 etc. if the code previously paused at 5.

Checkout the updated pen : https://codepen.io/anon/pen/PRGOxW

gawicks
  • 1,894
  • 15
  • 22