johan englund johan englund - 2 months ago 16
Javascript Question

Resume video playback after pause in JavaScript/HTML5?

I'm trying to pause a video and then resume the playback. But I presume I somehow need to clear the pause function? I've tried iterations of myVideo.play() and I can get it to play but only for short bursts. Any help would be much welcome.

<!DOCTYPE html>
<html>
<head>
<title> Html5 Video Test </title>
<meta charset="UTF-8">
</head>

<body> <
<div style="text-align:center">

<button onclick="playPause()">Play/Pause</button>

<video id="video1" width="420" autoplay>

<source src="test.mov" type="video/mov">
<source src="test.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
</div>

<script>


var myVideo = document.getElementById("video1");

myVideo.addEventListener("timeupdate", function(){
if(this.currentTime >= 1 * 2) {
this.pause();
}
});

</script>
</body>
</html>

Answer

If I understand correctly, you want your event listener to only fire once (so when you next play the video, it doesn't just immediately get paused again). If so, give this a shot:

var myVideo = document.getElementById("video1");

// Give this function a name so we can refer to it later.
function pauseOnce() {
   if (this.currentTime >= 1 * 2) {
       this.pause();

       // Our work is done. Remove the event listener. (We need a reference to
       // the function here.)
       this.removeEventListener("timeupdate", pauseOnce);
   }
}

myVideo.addEventListener("timeupdate", pauseOnce);