简体   繁体   English

JavaScript-在while循环中执行setTimeout

[英]javascript - do while loop setTimeout

I have read many topics about setTimeout but still i have a problem in understanding how can i implement this function to my loop. 我已经阅读了许多有关setTimeout主题,但是在理解如何将这个函数实现到循环中仍然存在问题。 I'll try to show you what I mean. 我会尽力告诉你我的意思。

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

Every time when the loop goes again, i try slow down code for a 2000 ms. 每次循环再次出现时,我都会尝试将代码减慢2000毫秒。 But this doesn't work. 但这是行不通的。

You have a problem with the one threaded nature of JavaScript (at least in this case - there are some exceptions, though). 您对JavaScript的单线程性质有疑问(至少在这种情况下-尽管有一些例外)。

What actually happens in your code is an endless while loop inside, in which plenty of setTimeout() functions are queued up. 代码中实际发生的是内部无休止的while循环,其中大量的setTimeout()函数排队。 But as your code never actually leaves the while loop, those callbacks wont be executed. 但是由于您的代码实际上从未离开过while循环,因此这些回调将不会执行。

One solution would be to trigger the next timeout function inside the setTimeout() callback like this: 一种解决方案是在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();
}

An alternative solution would be to use setIntervall() and clearIntervall() : 另一种解决方案是使用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