Last active
November 4, 2022 02:51
-
-
Save yairEO/9c7513d99b41c561b004ac296eb4569a to your computer and use it in GitHub Desktop.
Clear all browser timeouts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
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?
please make a jsbin showing where the problem is, because this code must and does work
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?
@zabytu - Proof the code is working as expected: https://jsbin.com/hasexel/edit?js,console
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
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