You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JQuery点击事件绑定Vimeo播放器pause监听器导致变量重复输出问题

问题根因
  • 重复日志和async异步逻辑无关,核心问题是每次点击按钮都会给播放器新增一个pause事件监听器:
    你在$('#button').on('click')的回调里每次都执行player.on('pause', 回调函数),点击n次后播放器就绑定了n个相同的pause监听回调,后续触发pause事件时n个回调会依次执行,自然就会打印n次相同日志。
  • 额外写法问题:player.pause().then()需要接收函数作为参数,你当前的写法是直接同步执行player.on,没有等待pause操作完成就绑定了事件,不符合异步逻辑的预期。
修复方案

推荐直接去掉不必要的pause事件绑定,主动调用pause完成后直接获取、赋值时长即可,修复后代码如下:

var duration = 0;
var currentDuration = 0;

async function asyncGetDuration() {
  return player.getDuration().then(function(duration) {
    return duration;
  })
}

function getDuration() {
  return asyncGetDuration();
}

// 按你描述的逻辑补全getCurrentDuration实现
async function getCurrentDuration() {
  return player.getCurrentTime().then(function(time) {
    return time;
  })
}

(async() => {
  // 初始赋值可保留
  duration = await getDuration();
  currentDuration = await getCurrentDuration();

  $('#button').on('click', async function() {
    // 等待暂停操作完成
    await player.pause();
    // 重新获取最新值覆盖变量
    duration = await getDuration();
    currentDuration = await getCurrentDuration();
    // 打印日志
    console.log('videoDuration:', duration);
    console.log('currentDuration:', currentDuration);
  });
})();

如果你确实需要监听所有pause触发场景(比如用户点击播放器自带的暂停按钮也需要执行逻辑),可以把player.on的绑定提到click事件外面,全局只绑定一次即可:

(async() => {
  duration = await getDuration();
  currentDuration = await getCurrentDuration();

  // 全局仅绑定一次pause监听
  player.on('pause', async function() {
    duration = await getDuration();
    currentDuration = await getCurrentDuration();
    console.log('videoDuration:', duration);
    console.log('currentDuration:', currentDuration);
  });

  $('#button').on('click', function() {
    player.pause();
  });
})();

内容的提问来源于stack exchange,提问作者Madame Green Pea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 08:06:04