Abhishek
Abhishek

Reputation: 4340

Break a series of timeout commands?

If I have a function like so:

function x()
{
    animate(a, 2000);
    animate(b, 3000);
    animate(c, 4000);
}

Where - a, b & c - are variables representing elements on the page, and the number is a parameter passed to an animate() function that uses it as a duration value for a timeout, like so:

function animate(src, dur)
{
    setTimeout(function() {
        src.style.opacity = 1;
    }, dur);
}

Everything so far is fine, but if I want the ability to break out of the animation loop, how do I go about it? Will clearTimeout() be what I'm looking for?

Upvotes: 0

Views: 65

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Variables that have been assigned a timeout, may be passed to the clearTimeout function, which will cease the function. You can store these variables in an array and easily clear all timeouts by iterating this array and passing the timeout to the clearTimeout function.

var timeouts = [];

/* Save timeouts into a variable and push to an array */
function animate(src, dur)
{
    var timeout = setTimeout(function() {
        src.style.opacity = 1;
    }, dur);
    timeouts.push(timeout);
}

/** Clear all timeouts**/
function clearTimeouts(){
   for(var i = 0; i < timeouts.length; i++){
     clearTimeout(timeouts[i]);
   }
}

//Create timeouts
x();
//Invoke clearTimeouts
clearTimeouts();

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

Yes, clearTimeout() is the right way to go:

function animate(src, dur)
{
    return setTimeout(function() {
        src.style.opacity = 1;
    }, dur);
}

And save returned identifier:

function x()
{
    var aId = animate(a, 2000);
    var bId = animate(b, 3000);
    var cId = animate(c, 4000);
}

Later you simply call clearTimeout(aId) or whichever you desire. BTW there is no loop in your code, setTimeout() executes only once, as opoosed to setInterval().

Upvotes: 0

Related Questions