Jquery / js delay looping
I have a 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 to add and remove a class (to simulate blinking) from each at infinity with some delay, but this code will do it all in one go. How can I solve this problem?
jQuery.each(status, function() { setTimeout(function() { $("#" + this).addClass('active'); }, 3000); }); You configure everything to start immediately. Multiply by index every time.
$('#ready, #steady, #go').each(function(i) { var el=$(this); setTimeout(function() { el.addClass('active'); }, i * 3000); }); Note that i in the first case is 0, so if you want # to wait 3 seconds already, use (i+1) * 3000
In addition, $('#'+this) is the wrong syntax, it is $(this) , however this will not work inside setTimeout.
Use setInterval instead of setTimeout to start the infinate loop (if not cleared).
Try the following:
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/
I would say that you better hold on to the ultimate goal.
1) Set the function to red. at the end of the red function graph, yellow with a set timeout of 1000 ms. 2) At the end of the yellow graph 1000 ms timeout for red
3) At the end of the green graph, a timeout of 1000 ms for green.
4) run your code by calling red ()
Now it will loop endlessly with the inconvenience of multiplying your timeout.
If you hate this, I would use setInterval rather than setTimeOut, but you might need more math.