I'm building a mobile game with Twine (a storytelling engine that uses html, css and javascript) and would like to start playback of a background-video for 5 seconds via the push of a button. After 5sec the video should pause. If I hit the button again the video should continue for another 5sec (moving further down the timeline) and then pause agin.
This is what I have so far.
<video id="myVideo">
<source src="./video.mp4" type="video/mp4">
<source src="mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
<script>
var vid = document.getElementById("myVideo");
function playVid() {
vid.play();
}
</script>
<button onclick="playVid()" type="button">Play Video</button>
Can anybody help out?
Thx a lot
CodePudding user response:
You're probably looking for the setTimeout
function - after vid.play()
.
It schedules a function to run after a specified amount of time, and returns a reference to the timer so you can cancel it by calling clearTimeout
.
You will probably want to consider what you want to happen if someone clicks the button while the video is playing too.
CodePudding user response:
- Don't use
on*
inline attribute handlers. Use addEventListener instead - Place your
<script>
tag in a non render-blocking manner, right before the closing</body>
tag. - Use setTimeout to schedule a function call, or perform some code — after N milliseconds
// DOM utility functions:
const el = (sel, par) => (par||document).querySelector(sel);
// Task:
const elVideo = el("#myVideo");
const elPlayVideo = el("#playVideo");
const timePause = 5000; // ms time to pause
let playTimeout;
const playVideo = () => {
clearTimeout(playTimeout); // Clear any occurring timeouts
elVideo.play(); // Play video
elPlayVideo.disabled = true; // Disable click
playTimeout = setTimeout(() => {
elVideo.pause(); // Pause video
elPlayVideo.disabled = false; // Enable button click
}, timePause); // Wait N milliseconds
};
elPlayVideo.addEventListener("click", playVideo);
video {
height: 150px;
}
<video id="myVideo" src="https://raw.githubusercontent.com/Ahmetaksungur/aksvideoplayer/main/videos/video-360.mp4"></video>
<button id="playVideo" type="button">Play Video</button>
<!-- Stop using inline on* handlers attributes. -->
<!-- <script> should go here, right before the closing `</body>` tag. -->