简体   繁体   中英

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. 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. 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).

What actually happens in your code is an endless while loop inside, in which plenty of setTimeout() functions are queued up. But as your code never actually leaves the while loop, those callbacks wont be executed.

One solution would be to trigger the next timeout function inside the setTimeout() callback like this:

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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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