console log inside a setTimeout unexpected delay

380 views Asked by At

The following code gives an unexpected result. It only waits for the 1sec delay (and not the 5 seconds specified by the delayBySeconds() function) then prints the output as given below.

function func(){
  const delaySeconds = 5;
  console.log("Alpha");
  setTimeout(()=> {console.log("Beta");}, 1000);
  console.log("Gamma");
  
  delayBySeconds(delaySeconds);
  console.log(`${delaySeconds} seconds passed`);
}

function delayBySeconds(sec){
  let start = now = Date.now();
  while((now - start) < (sec * 1000)){
    //console.log(now);
    now = Date.now();
  }
}

func();

Output:

"Alpha"
"Gamma"
"5 seconds passed"
"Beta"

Also, if console.log(now) is reactivated inside delayBySeconds(), the delay takes effect, otherwise the '5 seconds passed' gets printed immediately after "Gamma". Another unexpected result is that if instead of ()=> , I just use bare console.log("Beta") in argument to setTimeout(), "Beta" gets printed before "Gamma". Any suggestions what is causing this?

0

There are 0 answers