取消所有Javascript的setTimeouts和setIntervals [英] Cancel all Javascript's setTimeouts and setIntervals

查看:74
本文介绍了取消所有Javascript的setTimeouts和setIntervals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定的秒数后取消所有JS setTimeout,setInterval和requestAnimationFrame的正确方法是什么?

What's the proper way to cancel all JS setTimeout , setInterval and requestAnimationFrame after a given amount of seconds ?

编辑:对不起,我应该解释更多!代码来自数据库或某些API,因此我无法跟踪超时,raf或间隔ID。所以我没有定时器的ID,我可以很容易地将你清除为interInterval或clearTimeout或cancelAnimationFrame。我知道我必须使用它们,但我不知道如何获取所有动画ID(如果有的话)。

Sorry, I should have explained more! The code comes from either Database or some API, so I cannot keep track of the timeout,raf or interval IDs. So I don't have the IDs of the timers that I can easily you to clearInterval or clearTimeout or cancelAnimationFrame. I know I have to use them, but I don't know how to get all the animation IDs (if there are any).

推荐答案

你需要保留你创建的每个间隔,超时和requestAnimationFrame的Id,并在它们上调用 window.clearInterval(id)等。

You need to keep the Id of each interval, timeout and requestAnimationFrame you've created and call window.clearInterval(id) etc. on them.

一个简单的hackish /蛮力方式可以这样:

A verfy hackish/brute force way to do it would be something like:

for (var i = 1; i < 99999; i++) {
    window.clearInterval(i);
    window.clearTimeout(i);
    window.mozCancelAnimationFrame(i); // Firefox
}

但我不建议这样做。

更新:

在一段时间后执行此操作:

To do it after a certain amount of time:

setTimeout(function () {
   for (var i = 1; i < 99999; i++) {
        window.clearInterval(i);
        window.clearTimeout(i);
        window.mozCancelAnimationFrame(i); // Firefox
    }
}, 3000); // After 3 seconds

更新2:

如果你没有为每次超时等保留一个参考,我不相信有比蛮力方式更好的方法,所以要使它更容易做到(如通过此SO回答)建议,您可以覆盖默认的setInterval:

I don't believe there is a better way than the brute force way if you don't keep a reference for each time out etc, so to make it a bit easier to do that (as suggested by this SO answer), you could override the default setInterval:

var intervals = new Array();
window.oldSetInterval = window.setInterval;
window.setInterval = function(func, interval) {
    intervals.push(oldSetInterval(func, interval));
}

// Now you can loop over intervals and clear them 
// one by one when ever you want to.

for (var interval in intervals) {
   window.clearInterval(interval);
}

该示例显示了如何为 setInterval ,但当然可以在 setTimeout requestAnimationFrame 上以相同的方式完成。

The example shows how to do it for setInterval, but could of course be done the same way on setTimeout and requestAnimationFrame as well.

这篇关于取消所有Javascript的setTimeouts和setIntervals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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