javascript-do while循环设置超时
我已经阅读了许多关于javascript-do while循环设置超时,javascript,Javascript,我已经阅读了许多关于setTimeout的主题,但在理解如何在循环中实现此函数时仍然存在问题。 我会尽力让你明白我的意思 function RandomHit(anyArray) { var turechange = false; do{ setTimeout(function(){ var random = Math.floor(Math.random()*2); if(random===0)
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毫秒。但这不起作用。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()
:
参见示例,这似乎基本上是同一个问题我不清楚你的问题,但你应该使用
setInterval()
和clearInterval()
而不是loop
和setTimeout()
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 );
}