Calling the next timeout function inside the setTimeout() doesn’t delay before executing the function

Why this code that triggering the next timeout function inside the setTimeout() callback, from this link does work?

RandomHit();

function RandomHit() {
    var turechange = false;

    function timerFct(){
      var random = Math.floor(Math.random()*2);
      if(random===0)
      {
          turechange = true;
          jQuery('#result').append("<br />Result: " + random);
      }
      if(random===1)
      {
          jQuery('#result').append("<br />Result: " + random);
      }

      if( !turechange ) {
        setTimeout( timerFct, 2000 );
      }
    }

    timerFct();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">Please run repeatedly until the result become 1 and wait for the coming result..</div>

While this one that does the same calling the next timeout function inside the setTimeout(), is executing without any delay.. Any quick solution for this?

var countDown = 5;
timerFunc(countDown);

function timerFunc(count) {
    count -= 1;
    
    if (count !== 0) {
        jQuery('#result').append("<br />" + count);
        setTimeout(timerFunc(count), 3000);
    }
    else
        jQuery('#result').append("<br />Why it's not done slowly?");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>


Source: jquery

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.