JavaScript - 是否可以查看所有当前安排的超时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5817526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:27:29  来源:igfitidea点击:

JavaScript - Is it possible to view all currently scheduled timeouts?

javascript

提问by aroth

So I was wondering, is there any feasible way in JavaScript to view information about scheduled timeouts and intervals that you don't explicitly know about (I know setTimeoutand setIntervalreturn a handle that can be used to refer to the scheduled instance, but say that this is unavailable for one reason or another)? For instance, is there a way to use a tool like Chrome's JavaScript console to determine what timeouts are currently active on an arbitrary page, when they will fire, and what code will be executed when they fire? More specifically, say a page has just executed the following JavaScript:

所以我想知道,在 JavaScript 中是否有任何可行的方法来查看有关您没有明确知道的计划超时和间隔的信息(我知道setTimeoutsetInterval返回一个可用于引用计划实例的句柄,但是说这个由于某种原因不可用)?例如,有没有办法使用 Chrome 的 JavaScript 控制台之类的工具来确定当前在任意页面上处于活动状态的超时、何时触发以及触发时将执行哪些代码?更具体地说,假设一个页面刚刚执行了以下 JavaScript:

setTimeout("alert('test');", 30000);

Is there some code I can execute at this point that will tell me that the browser will execute alert('test');30 seconds from now?

是否有一些我可以在此时执行的代码会告诉我浏览器将在alert('test');30 秒后执行?

It seems like there theoretically should be some way to get this information since pretty much everything in JavaScript is exposed as a publicly accessible property if you know where to look, but I can't recall an instance of ever doing this myself or seeing it done by someone else.

似乎理论上应该有某种方法来获取此信息,因为如果您知道在哪里查看,JavaScript 中的几乎所有内容都作为可公开访问的属性公开,但我不记得自己曾经这样做或看到它完成的实例被别人。

采纳答案by sharp johnny

how about simply rewriting the setTimeout function to sort of inject custom logging functionality?

简单地重写 setTimeout 函数来注入自定义日志记录功能怎么样?

like

喜欢

var oldTimeout = setTimeout;
window.setTimeout = function(callback, timeout) {
  console.log("timeout started");
  return oldTimeout(function() {
    console.log('timeout finished');
    callback();
  }, timeout);
}

might work?

可能有用吗?

回答by Gareth

No, even the HTML5 spec(which is a rationalisation of the HTML 4.01 behaviour in current browsers, with additional features) doesn't specify a way to list the available callbacks.

不,即使是HTML5 规范(它是当前浏览器中 HTML 4.01 行为的合理化,具有附加功能)也没有指定列出可用回调的方法。

回答by Bar Goldinfeld

We've just published a package solving this exact issue.

我们刚刚发布了一个包来解决这个确切的问题。

npm install time-events-manager

With that, you can view them via timeoutCollection& intervalCollectionobjects.

这样,您就可以通过timeoutCollection&intervalCollection对象查看它们。

回答by Lawrence Cherone

You could also create a timer managermodule which will keep track of current timers and allow you to get, add, stop and stop all timers.

您还可以创建一个计时器管理器模块,它将跟踪当前计时器并允许您获取、添加、停止和停止所有计时器。

var timers = (function() {
  //
  var timers = []

  //
  const getIndex = (array, attr, value) => {
      for (let i = 0; i < array.length; i += 1) {
          if (array[i][attr] === value) {
              return i
          }
      }
      return -1
  };

  // add
  const add = (callback, time) => {
    var id = setTimeout(() => {
      let index = getIndex(timers, 'id', id)
      timers.splice(index, 1)
      callback()
    }, time)
    timers.push({
      id: id,
      time: time,
      debug: callback.toString()
    })
  };

  // get all active timers
  const all = () => timers

  // stop timer by timer id
  const stop = (id) => {
    if (!isNaN(id)) {
      let index = getIndex(timers, 'id', id)
      if (index !== -1) {
        clearTimeout(timers[index].id)
        timers.splice(index, 1)
      }
    }
  };

  // stop all timers
  const stopAll = () => {
    for (let i = 0; i < timers.length; i++) {
      clearTimeout(timers[i].id)
    }
    timers = []
  };

  return {
    add: add,
    all: all,
    stop: stop,
    stopAll: stopAll,
  };
})();

//
timers.add(function() {
  console.log("timeout 1 fired");
}, 1000)

timers.add(function() {
  console.log("timeout 2 wont get fired");
}, 2000)

timers.add(function() {
  console.log("timeout 3 fired");
}, 3000)

timers.add(function() {
  console.log("timeout 4 fired, timers", timers.all());
}, 4000)

timers.add(function() {
  console.log("timeout 5 fired");
}, 5000)

console.log('All timers', timers.all())

console.log("kill timer 2")
timers.stop(2)

Run the snippet to see it in action.

运行代码片段以查看它的运行情况。