javascript 循环延迟 jquery/js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15390436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:37:30  来源:igfitidea点击:

Looping with delay jquery / js

javascriptjqueryeachtrafficlight

提问by Vojtech Lacina

I have traffic light - 3 colors:

我有红绿灯 - 3 种颜色:

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

回答by Popnoodles

http://jsfiddle.net/9feh7/

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 iin the first instace is 0, so if you want #ready to wait 3 seconds use (i+1) * 3000

请注意,i在第一个实例中为 0,因此如果您希望 #ready 等待 3 秒,请使用(i+1) * 3000

Also, $('#'+this)is not correct syntax, it's $(this), however that won't work inside the setTimeout.

此外,$('#'+this)不是正确的语法,它是$(this),但是在 setTimeout 中不起作用。

Use setIntervalinstead of setTimeoutto run an infinate (unless cleared) loop.

使用setInterval而不是setTimeout运行无限(除非清除)循环。

回答by Rohan Kumar

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/

小提琴:http : //jsfiddle.net/M9NVy/

回答by j_mcnally

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

1) 设置红色功能。在红色功能计划黄色的末尾,设置超时 1000 毫秒。2) 在黄色调度结束时,红色超时 1000 毫秒

3) At the end of green schedule 1000ms timeout for green.

3) 在绿色调度结束时,绿色超时 1000 毫秒。

4) start your code by calling red()

4) 通过调用 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.

如果你讨厌那样,那么我会使用 setInterval 而不是 setTimeOut 但你可能需要更多的数学。