如何在JavaScript循环中添加延迟?

如何在JavaScript循环中添加延迟?,第1张

如何在JavaScript循环中添加延迟?

setTimeout()
函数是非阻塞的,将立即返回。因此,您的循环将非常快速地迭代,并且将快速连续地发起3秒超时触发。这就是为什么您的第一个警报会在3秒钟后d出,而其余所有警报都将连续不断地出现。

您可能要改用以下方式:

var i = 1;          //  set your counter to 1function myLoop () {//  create a loop function   setTimeout(function () {    //  call a 3s setTimeout when the loop is called      alert('hello');          //  your pre here      i++;          //  increment the counter      if (i < 10) { //  if the counter < 10, call the loop function         myLoop();  //  ..  again which will trigger another       }  //  ..  setTimeout()   }, 3000)}myLoop();//  start the loop

您也可以通过使用自调用函数将迭代次数作为参数来修饰它:

(function myLoop (i) {  setTimeout(function () {         alert('hello');          //  your pre hereif (--i) myLoop(i);      //  decrement i and call myLoop again if i > 0   }, 3000)})(10);  //  pass the number of iterations as an argument


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5004682.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-15

发表评论

登录后才能评论

评论列表(0条)

    保存