Limit HTML5 video playback

I know that I can infinitely loop a video using the "loop" attribute. But can I limit the number of video cycles to 5 times?

+7
html5 loops video
source share
1 answer

You will need to use JavaScript for this. Take a look at the snippet below:

var iterations = 1; document.getElementById('iteration').innerText = iterations; myVideo.addEventListener('ended', function () { if (iterations < 5) { this.currentTime = 0; this.play(); iterations ++; document.getElementById('iteration').innerText = iterations; } }, false); 
 <div>Iteration: <span id="iteration"></span></div> <video width="320" height="240" id="myVideo" controls> <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" /> <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" /> Your browser does not support the video tag. </video> 

So what's going on here ...?

  • Let's start by defining the iterations variable, which saves our current iteration. We set this as 1 .
  • We add an event listener to the myVideo video, which runs when the video ends.
  • Then we check that the variable iterations did not exceed our number of games, which are 5 .
  • We restart the video, reloading currentTime to 0 , and then use the play() function to start the video.
  • Then we increase the iterations variable by 1 , and the whole process starts again until our iterations variable reaches 5 , at which point it stops.
+15
source share

All Articles