Search code examples
htmlloopsvideo

Limit the number of times an HTML5 video plays


I know I can loop a video infinitely using the 'loop' attribute. But can I limit the number of times the video loops to perhaps 5 times?


Solution

  • You will need to use JavaScript to achieve this. Have a look at the snippet below:

    let iterations = 1;
    
    document.getElementById('iteration').innerText = iterations;
    
    document.getElementById('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 autoplay muted>
        <source src="//upload.wikimedia.org/wikipedia/commons/transcoded/c/c0/Big_Buck_Bunny_4K.webm/Big_Buck_Bunny_4K.webm.720p.vp9.webm" type="video/webm" />
        Your browser does not support the video tag.
    </video>

    So whats happening here...?

    1. We start by defining a variable called iterations which will store our current iteration. We set this as 1.
    2. We add an event listener to the myVideo video which fires when the video ends.
    3. We then check that the iterations variable hasn't exceeded our number of plays which is 5.
    4. We restart the video by resetting the currentTime to 0 and then using play() function to start the video.
    5. Then we increment the iterations variable by 1 and the whole process starts again until our iterations variable reaches 5 at which point it stops.