最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop looping an HTML5 video loop and let it play out to the end - Stack Overflow

programmeradmin3浏览0评论

I have a video that I would like to loop. After N seconds I would like it to stop looping. It should not stop immediately when the timer expires, but proceed to the end of the video and then stop.

This is my html code

 <video poster="images/banner-bg.jpg" id="bgvid" playsinline autoplay muted loop>
    <source src="vid/MM_Logo_Identity.mp4" type="video/mp4" id="bgvid1">
    </video>

script

document.getElementsByTagName('source').addEventListener('ended',myHandler,false);
function myHandler(e) {
    console.log('ended');
    setTimeout(function(){
        document.getElementsByTagName('source').play();
    }, 9000);
}; 

I have a video that I would like to loop. After N seconds I would like it to stop looping. It should not stop immediately when the timer expires, but proceed to the end of the video and then stop.

This is my html code

 <video poster="images/banner-bg.jpg" id="bgvid" playsinline autoplay muted loop>
    <source src="vid/MM_Logo_Identity.mp4" type="video/mp4" id="bgvid1">
    </video>

script

document.getElementsByTagName('source').addEventListener('ended',myHandler,false);
function myHandler(e) {
    console.log('ended');
    setTimeout(function(){
        document.getElementsByTagName('source').play();
    }, 9000);
}; 
Share Improve this question edited May 20, 2021 at 17:00 squarecandy 5,1074 gold badges39 silver badges49 bronze badges asked May 23, 2017 at 9:22 RijoRijo 3,0436 gold badges39 silver badges67 bronze badges 2
  • 2 Try to remove the loop from your html code – Le-Mr-Ruyk Commented May 23, 2017 at 9:23
  • ok bro got it thanks – Rijo Commented May 23, 2017 at 9:26
Add a ment  | 

3 Answers 3

Reset to default 3

You can remove the loop attribute, like this:

<video poster="images/banner-bg.jpg" id="bgvid" playsinline autoplay muted>
    <source src="vid/MM_Logo_Identity.mp4" type="video/mp4" id="bgvid1">
</video>

Try this code, it may useful to you.

document.getElementsByTagName('source').addEventListener('ended', function() { 
   this.currentTime = 1; 
}, false);

As several ments mentioned, you can remove the loop attribute to get it to stop looping. You could keep it in the HTML code and then just remove it when you want to stop looping.

<video poster="images/banner-bg.jpg" id="bgvid" playsinline autoplay muted loop>
    <source src="vid/MM_Logo_Identity.mp4" type="video/mp4" id="bgvid1">
</video>
// after 9 seconds, stop looping the video
setTimeout(function(){
    const video = document.getElementById('bgvid');
    video.removeAttribute("loop");

    // optional: go back to the poster image when the video pletes
    video.removeAttribute("autoplay"); // remove autoplay too so it doesn't start again
    video.addEventListener('ended', function() { video.load(); });
}, 9000);
发布评论

评论列表(0)

  1. 暂无评论