Backbencher.dev

JS Daily 6 - SetTimeout and Callstack

Last updated on 26 Nov, 2020

What is the output of following code?

console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
----o----

In the console, we see the output in following order:

"A"
"C"
"B"

This is an example of how call stack and event loop works. The delay is set to 0 for the setTimeout() function. Still, "B" is not printed immediately after "A". What happens is, line 1 prints "A". Line 2 then executes setTimeout() and it will set the callback function to executed later after the specified delay(Even if delay is 0). Then the control goes to line 3 and prints "C". After printing "C", the callstack is now empty to take and execute more functions. At that time, the callback function of setTimeout() is brought to callstack and executed. That prints "B" in the console.

--- ○ ---
Joby Joseph
Web Architect