2

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.

2
  • See eg stackoverflow.com/questions/22584035/…, that appears to be essentially the same question Commented Mar 23, 2014 at 11:35
  • I am not clear with your question, but you should use setInterval() and clearInterval() instead of loop and setTimeout() Commented Mar 23, 2014 at 11:36

1 Answer 1

7

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 );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.