我有以下代码:
var i = 0, count = 10, randomId;
function f(myArray) {
// this will get a random value from myArray
randomId = myArray[Math.floor( Math.random()*myArray.length )];
// displays the random value
alert (randomId);
i++;
if( i < count ){
setTimeout( f, 3000 );
}
}
f(myArray);
上面的代码可以工作,但只发出一个警报,然后就停止了。
但是,它可以正常工作(10 个循环),可以使用 alert("hi")
等基本警报,并删除 randomId 行。
就好像这个函数中任何复杂的东西都会阻塞循环,它只会处理基本的警报..
感谢任何帮助,谢谢:)
最佳答案
在您的setTimeout
中,您没有传递数组:
试试这个:
if( i < count ){
setTimeout(() => f(myArray), 3000 );
}
^ 创建一个 lambda 函数,以便您可以在超时时间内将值传递给回调。
var i = 0, count = 10, randomId;
function f(myArray) {
// this will get a random value from myArray
randomId = myArray[Math.floor( Math.random()*myArray.length )];
// displays the random value
alert (randomId);
i++;
if( i < count ){
setTimeout(() => f(myArray), 3000 );
}
}
f([1,2,3,4,5,6,7,8]);
关于javascript - JS - 我使用 setTimeout 的循环停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37119614/