javascript - 使用 Javascript 在特定时间后停止播放

我正在使用 Twine(一个使用 html、css 和 javascript 的讲故事引擎)构建一个手机游戏,并希望通过按下按钮开始播放背景 -video 5 秒钟。 5 秒后 video 应该暂停。如果我再次按下按钮,video 应该再继续 5 秒(进一步向下移动时间线),然后再次暂停。

这就是我到目前为止所拥有的。

<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>

有人可以帮忙吗?

多谢

回答1

// 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. -->

回答2

您可能正在寻找 setTimeout 函数 - 在 vid.play() 之后。

它安排一个函数在指定的时间后运行,并返回对计时器的引用,以便您可以通过调用 clearTimeout 取消它。

如果有人在 video 播放时单击按钮,您可能需要考虑您想要发生的情况。

相似文章

随机推荐

最新文章