Looping with delay jquery / js

Vojtech Lacina picture Vojtech Lacina · Mar 13, 2013 · Viewed 17.5k times · Source

I have traffic light - 3 colors:

<div class="green" id="ready"></div>
<div class="orange" id="steady"></div>
<div class="red" id="go"></div>

and array:

var status = ["ready", "steady", "go"];

I want add and remove class (to imitate flashing) from each in infinity loop with some delay, but this code make it all in one time. How can i solve it?

jQuery.each(status, function() {
    setTimeout(function() {
        $("#" + this).addClass('active');
    }, 3000);
});

Answer

Popnoodles picture Popnoodles · Mar 13, 2013

http://jsfiddle.net/9feh7/

You're setting all to run at once. Multiply by the index each time.

$('#ready, #steady, #go').each(function(i) { 
    var el=$(this);
    setTimeout(function() { 
        el.addClass('active');
    }, i * 3000); 
});

Note that i in the first instace is 0, so if you want #ready to wait 3 seconds use (i+1) * 3000

Also, $('#'+this) is not correct syntax, it's $(this), however that won't work inside the setTimeout.

Use setInterval instead of setTimeout to run an infinate (unless cleared) loop.