0

Possible Duplicate:
How do I add a delay in a JavaScript loop?

How can one delay after the completion of each iteration (or before) in a javascript for loop? Here is my code, but I need to have it 'sleep' for 6 seconds once it sets the color before it moves on to the next one in the list.

for (i = 0; i < switchers.length; i++) {
    $('#switchers ol li:nth-child(' + (i+1) + ')').css('color', 'green');
}

I have tried nesting a setTimeout, but that failed to work, and after searching around google, I decided to ask it here.

Community
  • 1
  • 1
slyv
  • 828
  • 1
  • 10
  • 18

2 Answers2

2

You can create a generic function which allows you to loop with a timeout interval. The code you would normally have in the "for" loop will go inside a function which you pass in as the last argument.

Like this:

var loopTimeout = function(i, max, interval, func) {
    if (i >= max) {
        return;
    }

    // Call the function
    func(i);

    i++;

    // "loop"
    setTimeout(function() {
        loopTimeout(i, max, interval, func);
    }, interval);
}
  • i : incrementing variable
  • max : how many times to loop
  • interval : timeout interval in ms
  • func : function to execute each iteration ("i" is passed as the only argument)

Example usage:

loopTimeout(0, switchers.length, 6000, function(i){
    $('#switchers ol li:nth-child(' + (i+1) + ')').css('color', 'green');    
});
nebs
  • 4,939
  • 9
  • 41
  • 70
1

You can use .each().

// timeout, in milliseconds to delay each iteration
var actionTimeout = 6000;

$('#switchers ol li').each(function(i, li) {
    setTimeout(function() {
        $(li).css('color', 'green');
    }, i * actionTimeout);
});

JSFiddle

Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61