Becky Becky - 1 year ago 68
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download