问题
I tried to create a repeat
function associating with an HTML5 video element, so it allows the player to repeat at the given time frame that I want.
I will call this function in the following sequence, repeat(1,3), repeat(5,7)
so I wish the player will repeat on time 1sec - 3sec when repeat(1,3)
is called, then 5sec - 7sec when repeat(5,7)
is called.
The player, however, keeps repeating time 1-3 sec frame when repeat(5,7)
is called. I know the issue is that video.currentTime >= 3
is true in repeat(5,7)
and the player goes to time 1sec again. But I am not sure what to do. Shall I remove the eventListener when repeat(5,7) is called? What is the proper way to handle this?
repeat(startTime, endTime) {
var video = document.getElementsByTagName('video')[0];
video.addEventListener('timeupdate', function() {
if (elem.currentTime >= endTime) {
elem.currentTime = startTime;
elem.play();
}
}, false);
}
回答1:
You will need to wrap the looping code in a named function so you can remove the old loop before setting up a new one. That is racked in funcLoop
below
I have also added a check so that if you're in the old loop and trigger a new one then it moves to the start (not sure if you need that, but seemed to make it more complete)
<video id="video" controls="controls" muted preload="metadata" >
<source src="video.mp4" type="video/mp4" />
</video>
<button onclick="repeat(1,3)">1-3</button>
<button onclick="repeat(5,7)">5-7</button>
<script>
var funcLoop
function repeat(startTime, endTime) {
var video = document.getElementById('video');
video.removeEventListener('timeupdate', funcLoop, false);
video.addEventListener('timeupdate', funcLoop=function(){
if (video.currentTime < startTime) {
video.currentTime = startTime;
}
if (video.currentTime >= endTime) {
video.currentTime = startTime;
}}, false);
video.play();
}
</script>
来源:https://stackoverflow.com/questions/44168839/html5-video-repeat-at-a-given-timeframe