我已经阅读了很多关于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);
}
Run Code Online (Sandbox Code Playgroud)
每当循环再次出现时,我会尝试减慢代码2000毫秒.但这不起作用.
你有一个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();
}
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用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 );
}
Run Code Online (Sandbox Code Playgroud)