如果父事件已经 运行 超过一段时间,如何 运行 一个函数

How to run a function if the parent event has been running for longer than a period of time

我有一个音频事件在缓冲中没有快速加载,我想更改一些事件。

所以在音频中,如果事件 'waiting' 被触发,除非超过 5 秒,否则什么也不做。然后 运行 函数 X。

这是一个示例代码:

$(audio).on("waiting", function () {
    // RUN AFTER 5 SECONDS
    console.log("This is taking way too long! Lets panic..");
    $play.append('<div class="icon-loading"></div>');
});

$(audio).on("playing", function () { 
    // This is the function that runs after wait is over
    console.log("Wait is over, it is loaded!");
    $play.append('<span class="icon-play-button"></span>');
});

提前致谢。

使用setTimeout和clearTimeout如下

let waitingTimeout;
$(audio).on("waiting", function() {
  // RUN AFTER 5 SECONDS
  waitingTimeout = setTimeout(() => {
    console.log("This is taking way too long! Lets panic..");
    $play.append('<div class="icon-loading"></div>');
  }, 5000);
});

$(audio).on("playing", function() {
  if (waitingTimeout) {
    clearTimeout(waitingTimeout);
    waitingTimeout = null;
  }
  // This is the function that runs after wait is over
  console.log("Wait is over, it is loaded!");
  $play.append('<span class="icon-play-button"></span>');
});