setTimeout在一个循环表达中只发生一次[英] setTimeout happens only once in a loop expression

本文是小编为大家收集整理的关于setTimeout在一个循环表达中只发生一次的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

这是一个例子:

function func1()
{
   setTimeout(function(){doSomething();}, 3000);
}
for(i=0;i<10;i++)
{
   func1();
}

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

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

推荐答案

您正在安排 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)
}
<!-- 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>

本文地址:https://www.itbaoku.cn/post/627331.html

问题描述

This is an example:

function func1()
{
   setTimeout(function(){doSomething();}, 3000);
}
for(i=0;i<10;i++)
{
   func1();
}

after executing it , the delay happens only in the first loop, but it didn't happen in the rest of the loops in that 'for' expression.

I want to make the delay happen in all of the loop and not only in the first time.
What's wrong in my code ?

推荐答案

You are scheduling 10 calls, but the problem is all are getting scheduled for the same time, ie after 3 seconds.

If you want to call them incrementally then you need to increase the delay in each call.

A solution will be is to pass a delay unit value to the func1 like

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