首页 > 解决方案 > 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吗?

标签: javascriptevent-handlinghtml5-videoremoveeventlistener

解决方案


我改用了一个计时器,现在它工作得很好。

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);
           }
      }

不过,如果有人不得不说什么,我仍将保持此帖子处于活动状态。


推荐阅读