我已经阅读了很多关于setTimeout
的主题,但我仍然有一个问题,就是如何理解如何在循环中实现这个功能。
我会试着告诉你我的意思。
function RandomHit(anyArray)
{
var turechange = false;
do{
setTimeout(function(){
var random = Math.floor(Math.random()*2);
if(random===0)
{
turechange = true;
console.log(random);
}
if(random===1)
{
console.log(random);
}
}, 2000);
}while(!turechange);
}
每当循环再次进行时,我会尝试减慢代码2000毫秒。但这不起作用。
答案 0 :(得分:6)
你遇到了JavaScript的一个线程特性的问题(至少在这种情况下 - 但是有一些例外)。
代码中实际发生的是一个无休止的while
循环,其中有大量setTimeout()
个函数排队。但是,由于您的代码实际上从未离开while
循环,因此不会执行这些回调。
一种解决方案是在setTimeout()
回调中触发下一个超时函数,如下所示:
function RandomHit(anyArray) {
var turechange = false;
function timerFct(){
var random = Math.floor(Math.random()*2);
if(random===0)
{
turechange = true;
console.log(random);
}
if(random===1)
{
console.log(random);
}
if( !turechange ) {
setTimeout( timerfct, 2000 );
}
}
timerFct();
}
另一种解决方案是使用setIntervall()
和clearIntervall()
:
function RandomHit(anyArray)
{
function timerFct(){
var random = Math.floor(Math.random()*2);
if(random===0)
{
turechange = true;
console.log(random);
}
if(random===1)
{
console.log(random);
}
if( turechange ) {
clearTimeout( timeoutHandler );
}
}
var turechange = false,
timeoutHandler = setInterval( timerFct, 2000 );
}