如何显示由setTimeout / setInterval生成的每个线程的列表 [英] How can I show a list of every thread running spawned by setTimeout/setInterval

查看:149
本文介绍了如何显示由setTimeout / setInterval生成的每个线程的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



可以吗?


我可以通过纯粹的JavaScript或浏览器中的任何类型的控制台来执行此操作。

谢谢



进一步说明:
我想调试一个动画库。如果有多个对象被动画,我想知道是否有多个计时器。

解决方案

正如其他人所说, setTimeout 不产生线程。如果你想要一个所有的超时ids列表(所以你可以取消它们,例如),请参见下面:






我不认为你可以得到一个所有超时ids列表,而不改变它们被调用时的代码。 setTimeout 返回一个id - 如果忽略它,那么您的JavaScript无法访问。 (显然,解释器可以访问它,但是您的代码不会。)



如果您可以更改代码,可以执行以下操作:

  var timeoutId = []; 

timeoutId.push(setTimeout(myfunc,100));

...确保 timeoutId 已声明全局范围(可能通过使用 window.timeoutId = [] )。






刚刚在我的头顶,但是要重新实现 setTimeout ,你必须这样做:

  var oldSetTimeout = setTimeout; 
setTimeout = function(func,delay){
timeoutId.push(oldSetTimeout(func,delay));
}

这没有测试,但它给了你一个起点。好的想法,molf!



编辑: aularon的答案给出了上述想法的更全面的实现。


I want to do this either by pure javascript or any sort of console in a browser or whatever.

Is it possible?

Thanks

Further explanations: I want to debug a library that does animations. I want to know if there's multiple timers created if there are multiple objects being animated.

解决方案

As others have mentioned, setTimeout doesn’t spawn a thread. If you want a list of all the timeout ids (so you can cancel them, for example) then see below:


I don’t think you can get a list of all timeout ids without changing the code when they are called. setTimeout returns an id—and if you ignore it, then it's inaccessible to your JavaScript. (Obviously the interpreter has access to it, but your code doesn't.)

If you could change the code you could do this:

var timeoutId = [];

timeoutId.push(setTimeout(myfunc, 100));

…Making sure that timeoutId is declared in global scope (perhaps by using window.timeoutId = []).


Just off the top of my head, but to reimplement setTimeout you’d have to do something like this:

var oldSetTimeout = setTimeout;
setTimeout = function (func, delay) {
    timeoutId.push(oldSetTimeout(func, delay));
}

This isn’t tested, but it gives you a starting point. Good idea, molf!

Edit: aularon's answer gives a much more thorough implementation of the above idea.

这篇关于如何显示由setTimeout / setInterval生成的每个线程的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆