Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping with delay jquery / js

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);
});
like image 986
Vojtech Lacina Avatar asked Mar 13 '13 16:03

Vojtech Lacina


2 Answers

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.

like image 141
Popnoodles Avatar answered Oct 06 '22 14:10

Popnoodles


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/

like image 41
Rohan Kumar Avatar answered Oct 06 '22 14:10

Rohan Kumar