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);
});
4
  • 1
    multiply the delay by the index of each iteration. Commented Mar 13, 2013 at 16:05
  • 2
    bring back the <blink> tag! Commented Mar 13, 2013 at 16:06
  • Work with a queue: stackoverflow.com/questions/2510115/… Commented Mar 13, 2013 at 16:07
  • 1
    BTW: green is ready and red is go...? Commented Mar 13, 2013 at 16:09

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh, thanks a lot - its working now, but with $('#'+status[i]).addClass('active'); Now, how can I run it in infinity loop?
use setInterval instead of setTimeout : developer.mozilla.org/en-US/docs/DOM/window.setInterval
@VojtechLacina, j_mcnally's response is to you.
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/

2 Comments

Why add another var i when you're already creating index?
As index will start from 0 which will add class active without any delay. We can use index+1 instead.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.