Alexander
Alexander

Reputation: 49

Change speed of Javascript increments while looping?

I am trying to build a script so that the second portion of an animation will only begin once the first is finished. I am attempting to accomplish this with an if statement and incrementing a variable after each loop. Theoretically, only after the first statement is finished counting through should the second begin.

URL: http://alexanderdiner.com/titletest/

function anim1() {
    if (i < cnt) {
        $imgOne.delay(1000).animate({bottom : '-=60px'}, 1000);
        i += 1;
        setTimeout(function() {anim1()}, 1000);
        console.log("The number is " + i);
    } else {
        cb();
    }
}

If you watch the console, it counts through too quickly and the second animation begins sooner then it should. Is there anyway to slow down the incrementation so the second animation executes correctly?

Upvotes: 1

Views: 931

Answers (2)

SeanCannon
SeanCannon

Reputation: 78006

Use a callback:

var _count    = 10,
    _distance = 60;

(function anim(){
    if(_count !== 0){
        _count-= 1;
    }
    $imgOne.animate({
        bottom:'-=' + _distance + 'px'
    },1000,function(){
        anim(); 
    });
})();

Demo: http://jsfiddle.net/AlienWebguy/wkgYv/ (changed direction of animation so you can see what's going on in the viewport)

Upvotes: 1

Joe
Joe

Reputation: 82654

animate takes a complete callback paramter

 $imgOne.delay(1000).animate({
    bottom : '-=60px'
  }, 1000, function() {
    anim1();
 });

Upvotes: 2

Related Questions