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 Oct 13, 2018

Import this into your code, at the very beginning, before any timeouts are defined and all setTimeout calls will be cached so they could be cleared at any given time

@Zelys-DFKH
Copy link

Not working for me. Executes but the length of the cache is always zero. Do the settimeouts somehow need to be separately assigned to the window object?

@yairEO
Copy link
Author

yairEO commented Jul 29, 2022

please make a jsbin showing where the problem is, because this code must and does work

@Zelys-DFKH
Copy link

Zelys-DFKH commented Jul 29, 2022

No errors or anything. window.clearTimeouts runs, but the cache is always empty, even though there are dozens of setTimeouts called. If I set the timeouts under the window object (window.setTimeout), then I get "_set is not a function. " Could I please see an example of this code inside a working script that doesn't otherwise use a window object?

@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