setTimeout在循环表达式中只发生一次

R00*_*R3z 1 javascript loops

这是一个例子:

function func1()
{
   setTimeout(function(){doSomething();}, 3000);
}
for(i=0;i<10;i++)
{
   func1();
}
Run Code Online (Sandbox Code Playgroud)

在执行它之后,延迟仅在第一个循环中发生,但在'for'表达式的其余循环中没有发生.

我希望延迟发生在所有循环中,而不仅仅是在第一次.
我的代码有什么问题?

Aru*_*hny 7

您正在安排10个呼叫,但问题是所有都在同一时间安排,即3秒后.

如果要逐步调用它们,则需要增加每次调用的延迟.

解决方案是将延迟单位值传递给func1类似物

function func1(i) {
  setTimeout(function() {
    doSomething();
  }, i * 500);//reduced delay for testing
}
for (i = 0; i < 10; i++) {
  func1(i + 1);
}

var counter = 0;

function doSomething() {
  snippet.log('called: ' + ++counter)
}
Run Code Online (Sandbox Code Playgroud)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<!-- To show result in the dom instead of console, only to be used in the snippet not in production -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Run Code Online (Sandbox Code Playgroud)