Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17471

Call a function after SetTimeout function

I have this code that make an image animation, but I want to call the function AnotherAction() when the animation is finished through the call clearTimeout(gLoop);

var Animate = function(){  
    Clear();  
    MoveDown();  
    gLoop = setTimeout(Animate,40);  
}

var MoveDown = function(){  
    // animation code  
    if(velocity==0){  
        clearTimeout(gLoop);  
        AnotherAction();  //Here is not working  
    }  
}

Where I supposed to make the call to AnotherAction()?

Upvotes: 1

Views: 2492

Answers (1)

Adam Rackis
Adam Rackis

Reputation: 83358

I think the problem is that you're clearing the timeout before you're setting it the next time. MoveDown is clearing the timeout, but as soon as control switches back to Animate, you're setting it again.

Try something like this:

var Animate = function(){  
    Clear();  
    if (MoveDown())
        gLoop = setTimeout(Animate,40);  
}

var MoveDown = function(){  
    // animation code  
    if(velocity==0){  
        AnotherAction();  //Here is not working  
        return false;
    }
    return true;  
}

Upvotes: 3

Related Questions