Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript-do while循环设置超时_Javascript - Fatal编程技术网

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 );
}