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. JavaScript - Is it possible to view all currently scheduled timeouts?
how about simply rewriting the setTimeout function to sort of inject custom logging functionality?
like
var oldTimeout = setTimeout;
window.setTimeout = function(callback, timeout) {
console.log("timeout started");
return oldTimeout(function() {
console.log('timeout finished');
callback();
}, timeout);
}
might work? How to stop all timeouts and intervals using javascript?
Updated answer after reading the duplicate I closed this question with -
It works and tested in Chrome on OSX
// run somethingvar 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
Is there a way to find out how many intervals are active in Javascript?
Wrap all Interval functions. For example:
myInterval = function(func, sec) {
myInterval.count = myInterval.count + 1 || 1;
setInterval(func, sec);
};
myInterval("console.log(1)", 3000);
myInterval("console.log(2)", 3000);
Thenconsole.log(myInterval.count); // => 2
The same for clearInterval, and Timeout functions javascript: Clear all timeouts?
They are not in the window object, but they have ids, which (afaik) are consecutive integers.
So you may clear all timeouts like so:
var id = window.setTimeout(function() {}, 0);
while (id--) {
window.clearTimeout(id); // will do nothing if no timeout with id is present
}
How can I get all timers in javascript?
Not by default, no. You could make your own module that lets you keep track of the timers, and which gives you the list. Roughly:
// ES2015+ version
const activeTimers = [];
exports.setTimeout = (callback, interval, ...timerArgs) => {
const handle = setTimeout((...args) => {
const index = activeTimers.indexOf(handle);
if (index >= 0) {
activeTimers.splice(index, 1);
}
callback(...args);
}, interval, ...timerArgs);
activeTimers.push(handle);
};
exports.getActiveTimers = () => {
return activeTimers.slice();
};
...then use its setTimeout
instead of the global one. How do I clear all intervals?
You can find the "highest" timer identifier by creating a new timer that does "nothing" (by giving it an empty function to run, scheduled to run decades in the future), and then clear every timer between ids 1 and that identifier, like so:
// Get a reference to the last interval + 1
const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
// Clear any timeout/interval up to that id
for (let i = 1; i < interval_id; i++) {
window.clearInterval(i);
}
However, note that this is not guaranteed to work: the HTML standard does not actually prescribe how timeout/interval identifiers get allocated, so the assumption that we'll get a reference to the "last interval identifier + 1" is merely that: an assumption. It might be true for most browsers at the time of this answer, but there is no guarantee that's that will still be the case even in the next version of the same browser. how to clear all javascript Timeouts?
__EDIT__
To manage a collection of timeouts (and intervals), you could use following snippet.This will allow to clear any timeouts or intervals set anywhere in code, although, you have to set this snippet before setting any timeout or interval. Basically, before processing any javascript code or external script which uses timeout/interval.
JS:
;(function () {
window.timeouts = {},
window.intervals = {},
window.osetTimeout = window.setTimeout,
window.osetInterval = window.setInterval,
window.oclearTimeout = window.clearTimeout,
window.oclearInterval = window.clearInterval,
window.setTimeout = function () {
var args = _parseArgs('timeouts', arguments),
timeout = window.osetTimeout.apply(this, args.args);
window.timeouts[args.ns].push(timeout);
return timeout;
},
window.setInterval = function () {
var args = _parseArgs('intervals', arguments),
interval = window.osetInterval.apply(this, args.args);
window.intervals[args.ns].push(interval);
return interval;
},
window.clearTimeout = function () {
_removeTimer('timeouts', arguments);
},
window.clearInterval = function () {
_removeTimer('intervals', arguments);
},
window.clearAllTimeout = function () {
_clearAllTimer('timeouts', arguments[0]);
},
window.clearAllInterval = function () {
_clearAllTimer('intervals', arguments[0]);
};
function _parseArgs(type, args) {
var ns = typeof args[0] === "function" ? "no_ns" : args[0];
if (ns !== "no_ns")[].splice.call(args, 0, 1);
if (!window[type][ns]) window[type][ns] = [];
return {
ns: ns,
args: args
};
}
function _removeTimer(type, args) {
var fnToCall = type === "timeouts" ? "oclearTimeout" : "oclearInterval",
timerId = args[0];
window[fnToCall].apply(this, args);
for (var k in window[type]) {
for (var i = 0, z = window[type][k].length; i < z; i++) {
if (window[type][k][i] === timerId) {
window[type][k].splice(i, 1);
if (!window[type][k].length) delete window[type][k];
return;
}
}
}
}
function _clearAllTimer(type, ns) {
var timersToClear = ns ? window[type][ns] : (function () {
var timers = [];
for (var k in window[type]) {
timers = timers.concat(window[type][k]);
}
return timers;
}());
for (var i = 0, z = timersToClear.length; i < z; i++) {
_removeTimer(type, [timersToClear[i]]);
}
}
}());
How to use it:
Set timeout(s)/interval(s) as usual:
var test1 = setTimeout(function(){/**/, 1000);
var test2 = setTimeout(function(){/**/, 1000);
Then you could use to clear both:clearAllTimeout(); // clearAllInterval(); for intervals
This will clear both timeouts (test1
& test2
)You can use some namespaces to clear only specific timers, e.g:
// first (optional) parameter for setTimeout/setInterval is namespace
var test1 = setTimeout('myNamespace', function(){/**/, 1000); // 'myNamespace' is current namespace used for test1 timeout
var test2 = setTimeout(function(){/**/, 1000); // no namespace used for test2 timeout
Again, clearAllTimeout();
will clear both timeouts. To clear only namespaced one, you can use:clearAllTimeout('myNamespace'); // clearAllInterval('myNamespace'); for namespaced intervals
This will clear only test1
timeout
You could for some reason wish to delete non namespaced timeouts only. You could then use:
clearAllTimeout('no_ns'); // clearAllInterval('no_ns'); for non namespaced intervals only
This will clear only test2
timeout in this example
See jsFiddle DEMO
__END of EDIT__
Old post specific to opening question here:
You could try that:
var timeouts = [];
timeouts.push(setTimeout(function() {
social2();
}, 5000));
timeouts.push(setTimeout(function() {
social1();
}, 5000));
//etc...
function clearAllTimeouts(){
for(var i = 0, z = timeouts.length; i < z; i++)
clearTimeout(timeouts[i]);
timeouts = [];
}
UPDATED following David Thomas commentvar timeouts = {'social' : [], 'antisocial' : []};
//a social timeout
timeouts.social.push(setTimeout(function() {
social1();
}, 5000));
//an anti-social timeout
timeouts.antisocial.push(setTimeout(function() {
antisocial1();
}, 5000));
function clearTimeouts(namespace){
for(var i = 0, z = timeouts[namespace].length; i < z; i++)
clearTimeout(timeouts[namespace][i]);
timeouts[namespace] = [];
}
//usage e.g
clearTimeouts("social");
Related Topics
Getting a Union of Two Arrays in JavaScript
Convert CSV Data into JSON Format Using JavaScript
Jquery: Change Event to Input File on Ie
What Is the JavaScript Mime Type for the Type Attribute of a Script Tag
Return Index of Greatest Value in an Array
Remove Whitespace and Line Breaks Between HTML Elements Using Jquery
How to Concatenate Regex Literals in JavaScript
Localstorage Object Is Undefined in Ie
Updating Svg Element Z-Index with D3
$(Document).Ready(Function() VS $(Function(){
How Does Setinterval and Settimeout Work
Google Map API - Multiple Icons in Wrong Spot
Quickest Way to Pass Data to a Popup Window I Created Using Window.Open()
Splicing a JavaScript Array from Within the Callback Passed to Foreach
JavaScript Request Fullscreen Is Unreliable
Read a Text File Using Node.Js