// 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);
// lets define some timeouts
setTimeout(()=> console.log('1s passed'), 1000); // should run
setTimeout(()=> console.log('2s passed'), 2000); // should be cleared
setTimeout(()=> console.log('3s passed'), 3000); // should be cleared
// lets clear them all after 1 and a half second:
setTimeout(()=> {
window.clearTimeouts()
}, 1500)
function clearAll(windowObject) {
var id = Math.max(
windowObject.setInterval(noop, 1000),
windowObject.setTimeout(noop, 1000)
);
while (id--) {
windowObject.clearTimeout(id);
windowObject.clearInterval(id);
}
function noop(){}
}
例如: $setTimeout (函数(A B){ run (a) ; run (b) ; } ,100,A B) ;)
... args 解决了这个问题。
var $timeouts = new Array();
function $setTimeout(...args)
{
var t = window.setTimeout(...args);
$timeouts.push(t);
return t;
}
function $clearTimeout(id)
{
if( $timeouts.indexOf(id) > -1 )
$timeouts = $timeouts.filter(n => n != id )
window.clearTimeout(id);
}
function $clearTimeouts()
{
while($timeouts.length)
window.clearTimeout($timeouts.pop());
}
对于老式浏览器,您需要使用其他方法来传递参数并从数组 $timeouts 中删除一个值。
var $timeouts = new Array();
function $setTimeout()
{
var t = window.setTimeout.apply( this, arguments );
$timeouts.push(t);
return t;
}
function $clearTimeout(id)
{
var index = $timeouts.indexOf(id);
if (index > -1) {
$timeouts.splice(index, 1);
}
window.clearTimeout(id);
}
function $clearTimeouts()
{
while($timeouts.length)
window.clearTimeout($timeouts.pop());
}
// example when I person types on search input
function typeOnSearch(time = 3000) {
// this will clear timeout
clearTimeout(window.typeOnSearchTimeOut);
// we create a timeout variable and added it to window, this way, we can access this in any function in our app.
window.typeOnSearchTimeOut = setTimeout( () => {
//enter what you like to do here, like fetch data
}, time);
}