jQuery Clear All Timeouts
Firstly, setTimeout() and clearTimeout() are pure JavaScript functions but are regularly used in JavaScript animations and the jQuery library. Sometimes when you have timeouts set up you may want to cancel them, in order to do this you need to store the settimeout in a variable.
Looping setTimeouts
Inside this loop the timeout is always going to be the same value: eg: TIMEOUT=1773
for(i=0; i<10; i++)
{
newTimeout = setTimeout(function()
{
console.log('TIMEOUT='+newTimeout);
});
}
If we tweak it a little with and throw in a setInterval to control the timing it works.
i = 0;
var interval = setInterval(function()
{
newTimeout = setTimeout(function()
{
console.log(this);
console.log('TIMEOUT='+newTimeout);
}, 100);
i++;
if (i > 10)
{
clearInterval(interval);
}
}, 200);
output:
Here we can clearly see the timeouts are being assigned an integer value. So that’s how we can clear them all using this:
Clear all setTimeouts
for(i=0; i<100; i++)
{
window.clearTimeout(i);
}
Further Reading
I wonder if it is possible to use jQuery to store timeout on object as data???
So then if an animation is queued using a setTimeout it could be stopped if it’s currently in animation or even before it’s started animating? hmm …
if (animateWidget !== undefined)
{
//only do 10 windows
for(i=0; i<10; i++)
{
window.clearTimeout(i);
}
//stop all animations on windows
$('.containerPlus').stop();
}
var animateWidget = setTimeout(function()
{
console.log('TIMEOUT: '+animateWidget);
EVI.FLEXIDASH.tileDash();
}, 300);