0

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?

Hamid Ali
  • 29
  • 6
  • Does this answer your question? [Understanding the Event Loop](https://stackoverflow.com/questions/21607692/understanding-the-event-loop) – ggorlen Oct 07 '20 at 02:06
  • All synchronous code is going to run before the task queue is going to even be looked at. You'd have to make `delayBySeconds` asynchronous for this to work as you expect. As for the beta being printed, you're calling `console.log` immediately instead of passing it in as the body of a callback function – ggorlen Oct 07 '20 at 02:27
  • @ggorlen Thanks. It clears the point (and again it's a remider for me) that whenever a function name is written with parentheses () , even when passing it to another function, it will immediately invoke it. So that's clear. But the second problem is that the delayBySeconds function apparently isn't async. Why doesn't it block execution for 5 seconds while continouly reading and comparing Date.now() in a while loop. – Hamid Ali Oct 07 '20 at 03:36
  • It does block execution, preventing the event loop or renderer from running. If you add a button, it can't respond to clicks during the 5-second busy loop. See [this video](https://www.youtube.com/watch?v=8aGhZQkoFbQ). – ggorlen Oct 07 '20 at 05:06
  • *"delayBySeconds function apparently isn't async"* .. that is very true... it runs continuosly for 5 seconds blocking anything else from running. The next thing that runs is synchronous code that was queued (the log of "seconds passed") and then the asynchronous setTimeout that gets pushed to end of event loop (after synchronous code) by default – charlietfl Oct 07 '20 at 13:03

0 Answers0