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.

0

2 Answers 2

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');    
});
Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

"That doesn't actually work"... care to actually explain?
That doesn't make sense.
"All functions will see the same value i: switchers.length". The timeout is the loop iteration multiplied by 6000...
It will work if you wrap the code inside the loop in an immediately executed function expression: (function(i){ ... }(i));. That copies the value for each iteration into the parameter.
I understand what you mean now @melpomene, your explanation was unclear to me. I've updated my answer and included a better method that addresses the variable scope issues. I would appreciate it if you removed your downvote.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.