简体   繁体   English

如何在特定的时间间隔内停止javascript循环?

[英]how to stop a javascript loop for a particular interval of time?

i am using javascript for loop, to loop through a particular array and alert it's value. 我正在使用javascript for循环,循环一个特定的数组并提醒它的价值。 I want that after every alert it should stop for 30 seconds and then continue...till the end of loop. 我希望在每次警报后它应该停止30秒然后继续......直到循环结束。 my code goes here.. 我的代码在这里..

    for(var i=0; i<valArray.lenght; i++)
    {
        alert("The value ="+valArray[i]);
        //stop for 30seconds..      
    }

i have used setTimeout() function, but it is not working...as loop end iterating but do not pause for 30seconds interval... is there any other way such as sleep function in PHP?? 我已经使用了setTimeout()函数,但是它没有工作...作为循环结束迭代,但是没有暂停30秒间隔...有没有其他方法,如PHP中的睡眠功能?

for (var i = 0; i < valArray.length; i++)
  (function(i) {
    setTimeout(function() {
      alert(valArray[i]);
    }, i * 30000);
  })(i);

Edited to fix the closure loop problem. 编辑修复闭包循环问题。

There is no sleep function in JavaScript. JavaScript中没有睡眠功能。 You can refactor above code to: 您可以将以上代码重构为:

function alert_and_sleep(i) {
   alert("The value ="+valArray[i]);
   if(i<valArray.length) {
     setTimeout('alert_and_sleep('+(i+1)+')',30000);
   }
}
alert_and_sleep(0);

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

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