Viewing all the timeouts/intervals in javascript?
I don't think there is a way to enumerate active timers, but you could override window.setTimeout
and window.clearTimeout
and replace them with your own implementations which do some tracking and then call the originals.
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);};
Of course, you might not always call clearTimeout
, but this would at least give you some way to track what is happening at runtime.
I made a Chrome DevTools extension that shows all intervals. Cleared ones are greyed out.
Instead of just have a count of timers, here is an implementation which stores all timerid's into an array. It only shows active timers while the accepted answer only counts calls to 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));
This is how you can get the count of active timers on the page:
timers.length;
This is how you can remove all active timers:
for(var i = timers.length; i--;) clearInterval(timers[i]);
Known limitations:
- You can only pass a function (not a string) to
setTimeout
with this monkey patch. - The function assumes
clearInterval
andclearTimeout
do the same, which they do but it could change in the future.