如何使用javascript停止所有超时和间隔? [英] How to stop all timeouts and intervals using javascript?
问题描述
我正在开发一个包含许多运行超时和间隔的ajax Web应用程序。现在我需要清除所有正在运行的超时和间隔。是否有一种简单的方法可以阻止所有内容而无需存储每个超时和间隔ID并迭代它们并清除它们?
I'm working on an ajax web appliation which contains many running timeouts and intervals. And now I need to clear all running timeouts and intervals sometimes. Is there a simple way to stop everything without need to store every timeout and interval ID and iterate through them and clear them?
推荐答案
阅读完副本后更新的答案我用 -
Updated answer after reading the duplicate I closed this question with -
在OSX上的Chrome浏览器中工作和测试
It works and tested in Chrome on OSX
// run something
var id1 = setInterval(function() { console.log("interval", new Date())}, 1000);
var id2 = setTimeout(function() { console.log("timeout 1", new Date())}, 2000);
var id3 = setTimeout(function() { console.log("timeout 2", new Date())}, 5000); // not run
setTimeout(function() { console.log("timeout 3", new Date())}, 6000); // not run
// this will kill all intervals and timeouts too in 3 seconds.
// Change 3000 to anything larger than 10
var killId = setTimeout(function() {
for (var i = killId; i > 0; i--) clearInterval(i)
}, 3000);
console.log(id1, id2, id3, killId); // the IDs set by the function I used
注意:看了在具有数字类型的窗口对象 - 有趣的是,IE分配了一个8位数字,FF是一个以2开头的单个数字
NOTE: Looked at window objects that had a typeof number - funnily enough IE assigns an 8 digit number, FF a single digit starting with 2
这篇关于如何使用javascript停止所有超时和间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!