Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@johan
Created December 11, 2016 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johan/30278fd971e6a20eb6af3566d2ad621b to your computer and use it in GitHub Desktop.
Save johan/30278fd971e6a20eb6af3566d2ad621b to your computer and use it in GitHub Desktop.
A browser functionality fill-in I ended up writing and sharing on http://stackoverflow.com/questions/3141064/how-to-stop-all-timeouts-and-intervals-using-javascript to batch cancel javascript's basic deferred execution functions.
(function(deferFunctions) {
for (var setter in deferFunctions) (function(setter, clearer) {
var ids = [];
var startFn = window[setter];
var clearFn = window[clearer];
function clear(id) {
var index = ids.indexOf(id);
if (index !== -1) ids.splice(index, 1);
return clearFn.apply(window, arguments);
}
function set() {
var id = startFn.apply(window, arguments);
ids.push(id);
return id;
}
set.clearAll = function() { ids.slice(0).forEach(clear); };
if (startFn && clearFn) {
window[setter] = set;
window[clearer] = clear;
}
})(setter, deferFunctions[setter]);
})(
{ setTimeout: 'clearTimeout'
, setInterval: 'clearInterval'
, requestAnimationFrame: 'cancelAnimationFrame'
});
// Some example timers of all types:
requestAnimationFrame(console.error);
setInterval(console.info, 1000, 'interval');
setTimeout(alert, 0, 'timeout');
// Now you can clear all deferred functions
// by execution type, whenever you want to:
window.setTimeout.clearAll();
window.setInterval.clearAll();
window.requestAnimationFrame.clearAll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment