简体   繁体   English

如何在 For 循环中使用超时?

[英]How to use timeOuts in For loops?

So, I'm trying to use create a loop which does this:所以,我正在尝试使用创建一个循环来执行此操作:

setTimeout(function() {           
    console.log("Hey!");

    setTimeout(function() {           
       console.log("Hey!");

       setTimeout(function() {           
       console.log("Hey!");

       }, 1000);

    }, 1000);

 }, 1000);

So, I tried it like this.所以,我是这样试的。

for (i = 0; 1 < 3; i++){
    setTimeout(function() {           
    console.log("Hey!");
}, 1000);
}

How ever, it's not working.然而,它不起作用。

Doing some research I've noticed this is because the timeOuts are getting added to each other with each loop.做了一些研究,我注意到这是因为每次循环都会将超时时间相互添加。 How can I work around this?我该如何解决这个问题?

You have to recursively call the time outs, so write a function that takes an argument of the current number of attempts.您必须递归调用超时,因此编写一个函数,该函数采用当前尝试次数作为参数。 Have it do an operation, and then call itself with the attempts argument += 1.让它做一个操作,然后用尝试参数 += 1 调用它自己。

You should pass a number of attempts as a safeguard so you can tell the function not to call itself if the attempts number is > some limit, to avoid infinite loops.您应该传递多次尝试作为保护措施,以便您可以告诉函数在尝试次数大于某个限制时不要调用自身,以避免无限循环。

Something like:就像是:

timedLog(attempts) {
  console.log('Hey!');
  if (attempts > 10) {
    return;
  } else {
    setTimeout(function() { timedLog(attempts + 1); }, 1000);
  }
}

It doesn't look like a for loop anymore, but it's the same principle.它看起来不再像 for 循环,但原理相同。

If the output of each function is the same, and you want to print it in the same interval, then you could use setInterval .如果每个函数的输出相同,并且您希望以相同的间隔打印它,那么您可以使用setInterval

function myInterval() {
  return setInterval(function(){
    console.log("Hey!");
  }, 1000);
};

var id = myInterval();

It will repeat forever, so you would have to stop it, in this case, after 3000 ms.它将永远重复,因此您必须在3000毫秒后停止它,在这种情况下。

setTimeout(function(){
   clearInterval(id);
}, 3000);

Just use a loop, increasing the timeout interval each time:只需使用循环,每次增加超时间隔:

for (let i = 0; 1 < 3; i++){
    setTimeout(function() {           
        console.log("Hey!");
    }, i*1000);
}

(Note, that if your callback function depended on i , this won't work as expected if you use var instead of let in the for loop header. The reason is to do with closures - there are many questions about this on SO. But it works perfectly with let - and there are other simple enough fixes if for some reason you can't use let .) (请注意,如果您的回调函数依赖于i ,那么如果您在for循环标头中使用var而不是let ,这将无法按预期工作。原因与闭包有关 - 在 SO 上有很多关于此的问题。但是它与let完美配合 - 如果由于某种原因您不能使用let ,还有其他足够简单的修复。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM