Skip to content

Instantly share code, notes, and snippets.

@zakirt
Last active May 21, 2020 05:30
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 zakirt/daf104745761c2217d4d56153d5c72fd to your computer and use it in GitHub Desktop.
Save zakirt/daf104745761c2217d4d56153d5c72fd to your computer and use it in GitHub Desktop.
Provides the ability to clear all timeouts in JavaScript. Uses Proxy objects to intercept setTimeout & clearTimeout functions.
/*
* Clears all timeouts while addressing the concern raised in the commment #11069768
* related to HTML5 spec for timer IDs.
* https://stackoverflow.com/questions/8860188/javascript-clear-all-timeouts#comment-11069768
*
* The example uses IIFE, but can be easily converted into a Node, or ES6 module.
* Proxies are used to intercept native setTimeout and clearTimeout functions, so that
* we can store the timeouts in the Set collection object.
* Calling the function without any parameters will clear all of the previously set timeouts.
*/
const {
setTimeout,
clearTimeout
} = ((globalContext, undefined) => {
const timeouts = new Set();
const setTimeout = new Proxy(globalContext.setTimeout, {
apply(target, thisArg, args) {
const tm = target.apply(thisArg, args);
timeouts.add(tm);
return tm;
}
});
const clearTimeout = new Proxy(globalContext.clearTimeout, {
apply(target, thisArg, args) {
if (!args.length) {
return clearAllTimeouts(target, thisArg);
}
const tm = args[0];
return clearTimeoutById(target, thisArg, tm);
}
});
function clearAllTimeouts(target, thisArg) {
for (const tm of timeouts) {
target.call(thisArg, tm);
}
timeouts.clear();
}
function clearTimeoutById(target, thisArg, tm) {
if (timeouts.has(tm)) {
target.call(thisArg, tm);
timeouts.delete(tm);
}
}
return {
setTimeout,
clearTimeout
};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment