TL;DR:只需收听"timeupdate":
video.addEventListener("timeupdate", function(){
if(this.currentTime >= 5 * 60) {
this.pause();
}
});
在 JavaScript 中等待某事的常用方法是等待事件或超时。在这种情况下超时是没有问题的,用户可以自己暂停视频。在这种情况下,停靠站不会在您的特定时间,而是更早。
定期检查时间成本也太高:要么检查过于频繁(因此浪费宝贵的处理能力),要么检查不够频繁,因此您不会在正确的时间停下来。
然而currentTime 是一个可检查的属性,幸运的是,媒体元素有timeupdate 事件,描述如下:
当前播放位置更改为正常播放的一部分或以特别有趣的方式更改,例如不连续。
由此得出结论,您可以简单地在timeupdate 上收听,然后检查您是否通过了标记:
// listen on the event
video.addEventListener("timeupdate", function(){
// check whether we have passed 5 minutes,
// current time is given in seconds
if(this.currentTime >= 5 * 60) {
// pause the playback
this.pause();
}
});
请注意,只要用户尝试跳过超过 5 分钟,此操作就会暂停。如果您想允许跳过并且仅在超过 5 分钟标记的初始暂停视频,请删除事件侦听器或引入某种标志:
var pausing_function = function(){
if(this.currentTime >= 5 * 60) {
this.pause();
// remove the event listener after you paused the playback
this.removeEventListener("timeupdate",pausing_function);
}
};
video.addEventListener("timeupdate", pausing_function);