Lena
Lena

Reputation: 39

wait for animation in for loop to finish

I'd like to animate a few objects using a for loop. the code looks like this:

for (var i = 0; i < 5; i++) {
    $('.el-' + i).animate({
        // code
    }, 5000);
}

how can I make the for loop to wait for animate to finish? is that possible? only one element should be animated at a time.

Upvotes: 1

Views: 564

Answers (2)

Randy Casburn
Randy Casburn

Reputation: 14165

Use the callback as a recursive function.

const count = 5;
function oneAtATime(i) {
    $('.el-'+ i).animate({
        opacity: 'toggle'
    }, 1000, ()=>{if(i < count) oneAtATime(i+1)});
}
oneAtATime(0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="el-0">Zero</div>
<div class="el-1">One</div>
<div class="el-2">Two</div>
<div class="el-3">Three</div>
<div class="el-4">Four</div>

Upvotes: 0

James
James

Reputation: 22237

As mentioned by @AlainDoe, you can use the complete callback to trigger the next animation, something like this.

const animateFunc = (i) => {
  $(".el-" + i).animate({ // code }, 5000, "swing", () => {
    if (i < 5) {
      animateFunc(i + 1);
    }
  });
};

// start the first animation
animateFunc(0);

Upvotes: 1

Related Questions