Detect in Javascript when HTML5 <video> loop restarts?

后端 未结 3 1801
一个人的身影
一个人的身影 2021-02-07 12:37

I have a looping HTML5 video using , and I want to know when the video loops. The event listener play only fires when the vi

3条回答
  •  不知归路
    2021-02-07 12:58

    I just had to do this for mobile. You can't do the accepted answer on mobile because mobile requires user interaction to run play() again (in many cases and especially in most web views)

    The only thing we can rely on in "timeupdate" for this is currentTime==0. Since we know currentTime==0 is going to run in the "timeupdate" 2-7 times depending hardware/whatever, we can set a boolean to capture just the first time it runs by setting the boolean to false immediately after the condition is met, then on timer we can reset the bool.

    Best solution I can conceive. We should just have a "looped" event listener.

    let loopCount = 0;
    let throttle = true;
    document.querySelector('video').addEventListener("timeupdate", () => {
        const video = document.querySelector('video');
        if (video.currentTime === 0 && throttle) {
            throttle = false,
            loopCount += 1;
            console.log(loopCount);
            setTimeout(()=> { 
                throttle = true;
            }, 500);
        }
    }, true);

提交回复
热议问题