Oma*_*eji 78 javascript timeout setinterval
我正在编写一个利用JavaScript超时和间隔来更新页面的应用程序.有没有办法看到设置了多少间隔?我想通过设置数百个间隔来确保我不会意外地杀死浏览器.
这甚至是个问题吗?
Pau*_*xon 69
我不认为有一种方法可以枚举活动计时器,但你可以覆盖window.setTimeout和window.clearTimeout并用你自己的实现替换它们,这些实现会进行一些跟踪,然后调用原件.
window.originalSetTimeout = window.setTimeout;
window.originalClearTimeout = window.clearTimeout;
window.activeTimers = 0;
window.setTimeout = function(func, delay) {
window.activeTimers++;
return window.originalSetTimeout(func, delay);
};
window.clearTimeout = function(timerID) {
window.activeTimers--;
window.originalClearTimeout(timerID);
};
Run Code Online (Sandbox Code Playgroud)
当然,您可能并不总是调用clearTimeout,但这至少可以为您提供一些方法来跟踪运行时发生的情况.
NVI*_*NVI 26
我制作了一个Chrome DevTools扩展程序,显示所有间隔.被清除的人是灰色的.
crv*_*crv 10
看到Paul只覆盖了setTimeout,我想我会为setInterval/clearInterval共享一个计数器.
window.originalSetInterval = window.setInterval;
window.originalClearInterval = window.clearInterval;
window.activeIntervals = 0;
window.setInterval = function (func, delay)
{
if(func && delay){
window.activeIntervals++;
}
return window.originalSetInterval(func,delay);
};
window.clearInterval = function (intervalId)
{
// JQuery sometimes hands in true which doesn't count
if(intervalId !== true){
window.activeIntervals--;
}
return window.originalClearInterval(intervalId);
};
Run Code Online (Sandbox Code Playgroud)
这里有一个将所有timerid存储到数组中的实现,而不仅仅是计时器的数量.它仅显示活动计时器,而接受的答案仅计算对setTimeout
&的调用clearTimeout
.
(function(w) {
var oldST = w.setTimeout;
var oldSI = w.setInterval;
var oldCI = w.clearInterval;
var timers = [];
w.timers = timers;
w.setTimeout = function(fn, delay) {
var id = oldST(function() {
fn && fn();
removeTimer(id);
}, delay);
timers.push(id);
return id;
};
w.setInterval = function(fn, delay) {
var id = oldSI(fn, delay);
timers.push(id);
return id;
};
w.clearInterval = function(id) {
oldCI(id);
removeTimer(id);
};
w.clearTimeout = w.clearInterval;
function removeTimer(id) {
var index = timers.indexOf(id);
if (index >= 0)
timers.splice(index, 1);
}
}(window));
Run Code Online (Sandbox Code Playgroud)
这是您如何获取页面上活动计时器的计数:
timers.length;
Run Code Online (Sandbox Code Playgroud)
这是您删除所有活动计时器的方法:
for(var i = timers.length; i--;)
clearInterval(timers[i]);
Run Code Online (Sandbox Code Playgroud)
已知限制:
setTimeout
这个猴子补丁传递函数(不是字符串).clearInterval
并clearTimeout
执行相同的操作,但它们可能会在将来发生变化.我们刚刚发布了一个包来解决这个问题。
npm install time-events-manager
Run Code Online (Sandbox Code Playgroud)
这样,您就可以通过timeoutCollection
对象查看和管理它们(以及通过对象的 JavaScript 间隔intervalCollection
)。
timeoutCollection.getScheduled();
timeoutCollection.getCompleted();
timeoutCollection.getAll();
归档时间: |
|
查看次数: |
57687 次 |
最近记录: |