Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active November 4, 2022 02:51
Show Gist options
  • Save yairEO/9c7513d99b41c561b004ac296eb4569a to your computer and use it in GitHub Desktop.
Save yairEO/9c7513d99b41c561b004ac296eb4569a to your computer and use it in GitHub Desktop.
Clear all browser timeouts
// isolated layer wrapper (for the local variables)
(function(_W){
var cache = [], // will store all timeouts IDs
_set = _W.setTimeout, // save original reference
_clear = _W.clearTimeout // save original reference
// Wrap original setTimeout with a function
_W.setTimeout = function( CB, duration, arg ){
// also, wrap the callback, so the cache reference will be removed
// when the timeout has reached (fired the callback)
var id = _set(function(){
removeCacheItem(id)
CB.apply(null, arguments)
}, duration || 0, arg)
cache.push(id) // store reference in the cache array
// id reference must be returned to be able to clear it
return id
}
// Wrap original clearTimeout with a function
_W.clearTimeout = function( id ){
_clear(id)
removeCacheItem(id)
}
// Add a custom function named "clearTimeouts" to the "window" object
_W.clearTimeouts = function(){
console.log("Clearing " + cache.length + " timeouts")
cache.forEach(n => _clear(n))
cache.length = []
}
// removes a specific id from the cache array
function removeCacheItem( id ){
var idx = cache.indexOf(id)
if( idx > -1 )
cache = cache.filter(n => n != id )
}
})(window);
@yairEO
Copy link
Author

yairEO commented Jul 30, 2022

@zabytu - Proof the code is working as expected: https://jsbin.com/hasexel/edit?js,console

@Zelys-DFKH
Copy link

Very helpful. Thank you for that piece of genius.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment