HTML5 pause a video at certain points

Viewed 1410

I have a video and I would like to pause it at a couple different points depending on the current time of the video. There will be 3 stops, one at 5 seconds, one at 10 seconds and one at 15 seconds. At each stop, a button comes up to continue playing the video. I am not sure how to make this work because currentTime never hits these points exactly, so currently I have to use >= the time stops, which means that the 5 second stop point will continuously fire.

var video = $('#video').get(0);

video.addEventListener('timeupdate', function() {
    if(this.currentTime >= 5) {
        console.log('5 seconds');
        this.pause();
        $('button').css('display','block');
    }
    
    if(this.currentTime >= 10) {
      console.log('10 seconds');
      this.pause();
      $('button').text('Part 3');
      $('button').css('display','block');
    }
    
    if(this.currentTime >= 15) {
      console.log('15 seconds');
      this.pause();
      $('button').text('Part 4');
      $('button').css('display','block');
    }
});

$('button').click(function() {
  video.play();
  $('button').css('display','none');
});
button {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="video" autoplay>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4">
</video>

<button>Part 2</button>

1 Answers

As you've seen the timeupdate is not always at the exact interval. It can be several milliseconds out.

To fix the issue you have, you can store a variable which holds the last point in the video a timeupdate happened and include that in your if conditions:

var $video = $('#video');
var video = $video.get(0);

video.addEventListener('timeupdate', function() {
  var lastCheckedAt = $video.data('lastcheck') || 0;
  $video.data('lastcheck', this.currentTime);
  
  if (this.currentTime >= 5 && lastCheckedAt < 5) {
    console.log('5 seconds');
    this.pause();
    $('button').show();
  } else if (this.currentTime >= 10 && lastCheckedAt < 10) {
    console.log('10 seconds');
    this.pause();
    $('button').text('Part 3').show();
  } else if (this.currentTime >= 15 && lastCheckedAt < 15) {
    console.log('15 seconds');
    this.pause();
    $('button').text('Part 4').show();
  }
});

$('button').click(function() {
  video.play();
  $('button').hide();
});
button {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="video" autoplay>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4">
</video>

<button>Part 2</button>

Also note the use of show() and hide() instead of calling css() directly.

Related