繁体   English   中英

JavaScript-在while循环中执行setTimeout

[英]javascript - do while loop setTimeout

我已经阅读了许多有关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()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM