使用 javascript 延迟 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27443185/
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
delay a for loop with javascript
提问by Linda
I want to delay a "for loop" for a while but don't know how to do it.
我想将“for 循环”延迟一段时间,但不知道该怎么做。
For example. Let's say this "for loop" runs from 0 to 8 and after each i there should be a delay for 2 sek.
例如。假设这个“for 循环”从 0 到 8 运行,并且在每个 i 之后应该有 2 秒的延迟。
for (var i=0; i<8; i++{
do something...
wait for 2 sek. and go on with i=i++;
}
回答by metadings
You'll have to go that way:
你必须走那条路:
function jsHello(i) {
if (i < 0) return;
setTimeout(function () {
alert("Hello " + i);
jsHello(--i);
}, 2000);
}
jsHello(5);
or
或者
function jsHello(i) {
alert("Hello " + i);
if (--i > -1) {
setTimeout(function () { jsHello(i); }, 2000);
}
}
jsHello(5);
回答by jcbermu
Javascript doesn't have a wait command. The way to get this behavior is using setTimeout
:
Javascript 没有等待命令。获得这种行为的方法是使用setTimeout
:
for (var i=0; i<8; i++){
do_something(i);
}
function do_something(j) {
setTimeout(function() {
tasks to do;
}, 2000 * j);
}
Every time the function do_something()
is called, it executes "tasks to do"scheduled by 2000*i
milliseconds.
每次do_something()
调用该函数时,它都会执行以毫秒为单位调度的“要执行的任务”2000*i
。
回答by Evgeniy
To resolve this task you have to use closure - immediately invoke function witch be called on every iteration with i
as param, and setTimeout inside this function. In this case param you passed will be stored in scope and could be used in timeout callback:
要解决此任务,您必须使用闭包 - 立即调用在每次迭代中使用i
as param 和 setTimeout 调用的函数。在这种情况下,您传递的参数将存储在作用域中并可用于超时回调:
for (var i=0; i<8; i++) (function(t) {
window.setTimeout(function() {
//do anything with t
}, t*2000)
}(i))