javascript - removeEventListener("timeUpdate", myFunction) 在视频播放过程中不稳定
问题描述
一旦我的视频开始播放,就会添加一个事件监听器。那是
document.getElementById("myVideo").addEventListener("timeUpdate", myFunction);
然后就在视频结束之前,我希望在视频的最后几秒钟发生一些事情(也许是淡出)(或者为了简单起见,我只想写一些类似的东西alert("goodbye");
)。
当我使用这段代码时
var myVideo = document.getElementById ("myVideo");
function myFunction(){
if(myVideo.currentTime >= (myVideo.duration-3) )
{
alert("this goodbye message is supposed to be displayed only once and exactly three seconds before the video ends");
myVideo.removeEventListener("timeupdate", myFunction);
}
}
它适用于 Chrome,但不稳定。有时它可以正常工作,但有时在实际删除事件侦听器之前警报会持续弹出几次(这在我的情况下很糟糕)。在 Firefox 中,它甚至更糟,因为它会触发多次。我知道不同的浏览器会timeupdate
以非常不同的时间间隔触发事件。
所以你怎么看?我是否应该放弃
addEventListener()
removeEventListener()
这对夫妇并使用
setInterval()
clearInterval()
检查播放头的位置并在时机成熟时做一些事情。这样,我可以设置自己的时间间隔以保持一致性,而不是依赖于浏览器的时间间隔。但是有人知道是否有可靠的方法来做到这一点timeUpdate
吗?
解决方案
我改用了一个计时器,现在它工作得很好。
var checkThePlayheadPositionTenTimesASecond = setInterval(myTimer, 100);
function myTimer()
{
if(myVideo.currentTime >= (myVideo.duration-3) )
{
alert("this video is going to end in three seconds");
clearInterval(checkThePlayheadPositionTenTimesASecond);
}
}
不过,如果有人不得不说什么,我仍将保持此帖子处于活动状态。
推荐阅读
- c - 如何告诉编译器/CPU 在内核空间的代码中背靠背执行指令?
- c# - VSCODE 的 Nuget 找错地方了
- python - 如何使用带有“group_by”数据框的plot()在bar中显示每个变量的值?
- python - 如何在两个不同的数据框中找到同一列并返回每个数据框中同一列的索引
- css - 多行文本上的文本效果后的 CSS 行
- powershell - 如何使用powershell脚本在后台进程中获取进程名称?
- python - 从 NETCDF4 格式的网格化气象数据集创建时间序列
- r - ggplot2 不显示 Latex (knitr) 中的图形
- r - R:根据另一个数据集中的几个变量填写一个新列
- java - 杰克逊无法解析 ISO8601