1

Is the top-level code always executed first in Javascript even if we have a timer at 0 seconds?

Meaning, even if the timer is finished at 0s and the callback is added in the callback queue at 0s, the code after that timer runs before the timer shows results. If we run this below snippet, the result order is: "First" "second" "Timeout"

console.log('First');
setTimeout(()=> console.log('Timeout'), 0);
console.log('second')

Why is that?

  • 1
    Yes. Asynchronous code doesn't execute until the code returns to the event loop. – Barmar Dec 08 '21 at 21:26
  • What do you mean by "top-level code"? The first script that executed code on a page? Any code that is currently executing? Something else? – Bergi Dec 08 '21 at 21:28
  • Please [edit] your question to show examples of the kind of code you're talking about. – Heretic Monkey Dec 08 '21 at 21:29
  • possible duplicate of https://stackoverflow.com/questions/21607692/understanding-the-event-loop?noredirect=1&lq=1 – Bergi Dec 08 '21 at 22:29
  • Does this answer your question? [Why doesn't setTimeout(.., 0) execute immediately?](https://stackoverflow.com/questions/36904773/why-doesnt-settimeout-0-execute-immediately) – Heretic Monkey Dec 09 '21 at 13:44
  • 1
    See also [Why does a setTimeout delay of 0 still run after all other synchronous code in a for loop?](https://stackoverflow.com/q/49331947/215552), [Why setTimeout function in javascript calls after other line eventhough time is for zero seconds?](https://stackoverflow.com/q/40904061/215552), [Why is the `setTimeout` callback called after function execution, even if the delay is 0 ms?](https://stackoverflow.com/q/61580335/215552), etc. – Heretic Monkey Dec 09 '21 at 13:46

0 Answers0