视频播放事件每秒触发数千次

Video canplay event triggers thousands of times per second

我的页面加载函数中有以下 jQuery 代码:

$("#vid-pages").find("video").on('canplay', function() {
  $(this)[0].currentTime = $(this)[0].duration / 2;
  console.log($(this)[0].currentTime);
});

该容器中只有两个视频,none 页面上的其他任何地方。当我检查控制台时,它不断充斥着该代码块中返回的时间。有什么办法可以让这个触发器只触发一次,而不是一直触发?

当前时间更改后,浏览器需要从缓存或网络加载更多数据。这可以触发 canplay 事件。由于在事件处理程序中设置了时间,您将获得一个永无止境的循环(您可以通过选择视频,点击播放然后跳到中间)。这可能取决于浏览器。

MDN 上的

This page 对相关 canplaythrough 的说明如下(尽管不完全相同但有理由相信这也适用于 canplay,如使用 Firefox 的媒体活动页面所示:

Note: Manually setting the currentTime will eventually fire a canplaythrough event in firefox. Other browsers might not fire this event.

为避免取消订阅该事件,或使用 标志 强制在第二次触发事件时退出。

var initialPlay = false;

$("#vid-pages").find("video").on('canplay', function() {
  if (initialPlay) return;
  initialPlay = true;

  $(this)[0].currentTime = $(this)[0].duration / 2;
  console.log($(this)[0].currentTime);
});

要取消订阅,您需要使用非匿名函数。