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);
});
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With