5

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);
});
Vojtech Lacina
  • 340
  • 2
  • 3
  • 11

3 Answers3

15

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.

Popnoodles
  • 28,090
  • 2
  • 45
  • 53
3

Try this:

var status = ["ready", "steady", "go"];
var i=1;
jQuery(status).each(function(index,value) {
    var self=this;
    setTimeout(function() {
       $(self).addClass('active');
    }, 3000*i);
    i++;
});

Fiddle: http://jsfiddle.net/M9NVy/

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

I would say you are better off chaining for your end goal.

1) Setup a function for red. at the end of the red function schedule yellow with a set timeout 1000 ms. 2) At the end of yellow schedule 1000ms time out for red

3) At the end of green schedule 1000ms timeout for green.

4) start your code by calling red()

Now it will loop infinitely with out the awkwardness of multiplying your timeout.

If you hate that then I would use setInterval rather than setTimeOut but you may need more math.

j_mcnally
  • 6,928
  • 2
  • 31
  • 46