YonL
YonL

Reputation: 39

Execute all elements in a loop in a consecutive manner?

how can I execute a function in a loop in a way that the next element in the loop is only executed when the previous element has been done.

$(".welcome>p").each(function() {
    var $this = $(this);
    setTimeout(function() {
        $this.animate({
            opacity: 1
        }, 600);
    });

});

So, all the p element in this code will be running at the same time. How can I change it so that the p element will show up one by one by its order?

Thanks, YonL

Upvotes: 0

Views: 35

Answers (1)

charlietfl
charlietfl

Reputation: 171679

The first argument of each is index, so you could use that index to increment the setTimeout like:

$(".welcome>p").each(function( idx ) {
    var $this = $(this);
    setTimeout(function() {
        $this.animate({
            opacity: 1
        }, 600);
    }, idx * 600);

});

Upvotes: 3

Related Questions