Looping with delay jquery / js

17,623

Solution 1

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.

Solution 2

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/

Share:
17,623
Vojtech Lacina
Author by

Vojtech Lacina

Updated on June 06, 2022

Comments

  • Vojtech Lacina
    Vojtech Lacina about 2 years

    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
    Vojtech Lacina over 11 years
    Oh, thanks a lot - its working now, but with $('#'+status[i]).addClass('active'); Now, how can I run it in infinity loop?
  • j_mcnally
    j_mcnally over 11 years
    use setInterval instead of setTimeout : developer.mozilla.org/en-US/docs/DOM/window.setInterval
  • Popnoodles
    Popnoodles over 11 years
    @VojtechLacina, j_mcnally's response is to you.
  • Popnoodles
    Popnoodles almost 9 years
    Why add another var i when you're already creating index?
  • Rohan Kumar
    Rohan Kumar almost 9 years
    As index will start from 0 which will add class active without any delay. We can use index+1 instead.