JavaScript:超时循环

我希望我的for循环不应该一次执行,而是在每次迭代后等待超时。例如:


for(var i=0; i<10; i++) {

    console.log(i);

    //wait for 1000

}

我发现了很多关于堆栈溢出的解决方案,例如:


for (var i=0;i<=10;i++) {

   (function(ind) {

       setTimeout(function(){console.log(ind);}, 3000);

   })(i);

}

但是在所有实现中,循环最初等待3000毫秒,然后立即执行整个for循环。有没有一种方法可以等待1000毫秒后调用每次迭代。


慕容708150
浏览 406回答 3
3回答

回首忆惘然

不要在loops中创建函数,而是:(function fiveSeconds&nbsp; (n) {&nbsp; if (n < 5) setTimeout(function () {&nbsp;&nbsp;&nbsp; &nbsp; fiveSeconds ( n ); // Redo if n < 5 (and pass n)&nbsp; }, 1000);&nbsp;&nbsp;&nbsp; console.log( n++ );} (0)); // Initialize. n is 0上面的代码将以1秒的间隔记录从0-5的十个数字。现代浏览器(和IE10 +)(function fiveSeconds (n) {&nbsp; console.log( n++ );&nbsp; if (n <= 5) setTimeout( fiveSeconds, 1000, n ); // Redo if n <= 5 (and pass n)&nbsp;&nbsp;} (0)); // Initialize. n is 0

慕尼黑5688855

为什么不使用这样的东西:var i = 0var id = window.setInterval(function(){&nbsp; &nbsp; if(i >= 10) {&nbsp; &nbsp; &nbsp; &nbsp; clearInterval(id);&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; console.log(i);&nbsp; &nbsp; i++;}, 1000)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript