最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Looping with delay jqueryjs - Stack Overflow

programmeradmin4浏览0评论

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);
});

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);
});
Share Improve this question edited Mar 13, 2013 at 16:42 Vojtech Lacina asked Mar 13, 2013 at 16:04 Vojtech LacinaVojtech Lacina 3402 gold badges3 silver badges11 bronze badges 4
  • 1 multiply the delay by the index of each iteration. – Kevin B Commented Mar 13, 2013 at 16:05
  • 2 bring back the <blink> tag! – geedubb Commented Mar 13, 2013 at 16:06
  • Work with a queue: stackoverflow.com/questions/2510115/… – Jonny Sooter Commented Mar 13, 2013 at 16:07
  • 1 BTW: green is ready and red is go...? – Tim Büthe Commented Mar 13, 2013 at 16:09
Add a comment  | 

3 Answers 3

Reset to default 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.

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/

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.

发布评论

评论列表(0)

  1. 暂无评论