有没有办法清除所有的时间?

有没有办法从给定的窗口中清除所有的时间? 我想超时被存储在window对象的某个地方,但不能确认。

任何跨浏览器解决scheme是受欢迎

它们不在窗口对象中,但是它们具有ID(afaik)是连续的整数。

所以你可以像这样清除所有的超时:

 var id = window.setTimeout(function() {}, 0); while (id--) { window.clearTimeout(id); // will do nothing if no timeout with id is present } 

我认为最简单的方法是将所有的setTimeout标识符存储在一个数组中,在这些数组中你可以很容易地迭代到所有的setTimeout clearTimeout()

 var timeouts = []; timeouts.push(setTimeout(function(){alert(1);}, 200)); timeouts.push(setTimeout(function(){alert(2);}, 300)); timeouts.push(setTimeout(function(){alert(3);}, 400)); for (var i=0; i<timeouts.length; i++) { clearTimeout(timeouts[i]); } 

我对Pumbaa80的答案有一个补充,对于那些为旧IE开发的人可能会有帮助。

是的,所有主stream浏览器都将超时ID设置为连续整数( 规范不要求 )。 通过浏览器和浏览器的起始号码不同。 看起来,Opera,Safari,Chrome和IE> 8从一个基于Gecko的浏览器启动超时ID,从2和IE <= 8从一个随机数开始,奇妙地保存在标签刷新。 你可以自己发现它 。

所有在IE <= 8的while (lastTimeoutId--)循环中都会运行超过8位次并显示“ 此页面上的脚本正在导致Internet Explorer运行缓慢 ”消息。 所以,如果你不能保存所有你超时的ID或不想覆盖window.setTimeout你可能会考虑保存页面上的第一个超时ID和清除超时,直到它。

在早期页面加载时执行代码:

 var clearAllTimeouts = (function () { var noop = function () {}, firstId = window.setTimeout(noop, 0); return function () { var lastId = window.setTimeout(noop, 0); console.log('Removing', lastId - firstId, 'timeout handlers'); while (firstId != lastId) window.clearTimeout(++firstId); }; }); 

然后清除所有可能由外部代码设置的所有待处理的超时

如何将超时ID存储在全局数组中,并定义一个将函数调用委托给窗口的方法。

 GLOBAL={ timeouts : [],//global timeout id arrays setTimeout : function(code,number){ this.timeouts.push(setTimeout(code,number)); }, clearAllTimeout :function(){ for (var i=0; i<this.timeouts.length; i++) { window.clearTimeout(this.timeouts[i]); // clear all the timeouts } this.timeouts= [];//empty the id array } }; 

使用全局超时,其中所有其他函数都从中获取时间。 这将使所有的运行速度更快,更容易pipe理,尽pipe它会为你的代码添加一些抽象。

我们刚刚发布了一个解决这个问题的软件包。

npm install time-events-manager

有了这个,你可以通过timeoutCollectionintervalCollection对象查看所有超时和间隔。 还有一个removeAll函数可以清除集合和浏览器的所有超时/间隔。