Becky Becky - 2 months ago 7
Javascript Question

1 second gap within each() function

I need to execute a function inside a each() function every 1 second. How can I do this?

$('.items:visible').each(function(){
var id = this.id;
executeNow(i, s, id);
count++;
if(count==total){
///do something
}
});


Basically I need to have a 1 second gap each time the
executeNow();
is called inside this each() function.

Answer

You can write a simple run-away-timer yourself, like so:

var set = $('.items:visible').get();

(function loop( elem ) {
    executeNow( elem );

    if( set.length ) {
        setTimeout( function() {
            loop( set.shift() );
        }, 1000 );
    }
}( set.shift() ));

That way, timers cannot interfere or overlap. Classical you would just call a setTimeout with increasing timeout values, but the solution above is cleaner and more reliable.

Comments