
该
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欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)