Erasersharp Erasersharp - 3 months ago 19
Javascript Question

Waiting for each animation in loop to finish before running the next one

I'm looking to run a delay on the count up function, so whenever the finish class name of counter finishes it will then run the count up whenever the previous one has finished etc.

$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');

$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 4000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
});

Answer

This is not working with an each loop. You have to use the complete callback an do it by your own, because the animation is asynchron.

I would use a recursive, self-execution function. Pretty easy, just start the next one when completed.

var elements = $('.counter');
var current = 0;

(function next() {
    var $this = elements.eq(current),
        countTo = $this.attr('data-count');

    $({countNum: $this.text()}).animate({countNum: countTo}, {
        duration: 4000,
        easing: 'linear',
        step: function() {
            $this.text(Math.floor(this.countNum));
        },
        complete: function() {
            $this.text(this.countNum);

            if( (++current) < elements.length ) {
                next();
            }
        }
    });  
})();