Becky Becky - 5 months ago 18
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?

var id =;
executeNow(i, s, id);
///do something

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


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.