DEV Community

Shrey Banugaria
Shrey Banugaria

Posted on

Understanding Event Loop with an Interview Question

Here is the JS code, you have to guess the output. Also, you have to mention why that particular output


console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
setTimeout(() => console.log('D'), 0);
console.log('E');

If your answer is AE CBD. You are correct.
Let's see how

1 Synchronous Execution:

console.log('A'); and console.log('E'); are executed first because they are synchronous statements. They don't involve any waiting for asynchronous operations.

2 setTimeout and Promises:

setTimeout(() => console.log('B'), 0); and Promise.resolve().then(() => console.log('C')); are both asynchronous operations.
However, the delay specified in setTimeout (0 milliseconds) doesn't guarantee immediate execution after synchronous code.
Promises are typically processed before setTimeout callbacks due to the way JavaScript's event loop handles tasks.

3 Event Loop:

JavaScript uses an event loop to manage synchronous and asynchronous operations.
After executing synchronous code (console.log('A'); and console.log('E');), the event loop checks for any tasks in the "microtask queue."
Promises are queued in the microtask queue, while setTimeout callbacks are placed in the "task queue."

4 Microtask vs Task Queue:

The event loop processes the microtask queue before the task queue in each iteration.
Since Promise.resolve().then(...) creates a resolved promise immediately, it gets pushed to the microtask queue.

5 Execution Order:

Therefore, the resolved promise's callback (console.log('C'); gets executed first from the microtask queue.
setTimeout Callbacks:

After processing the microtask queue, the event loop moves to the task queue.
Even though both setTimeout callbacks have a delay of 0, they don't run immediately. They are placed in the task queue.
In the next iteration of the event loop, the task queue is processed, and both setTimeout callbacks are scheduled for execution.

6 Non-deterministic Order:

Due to the nature of the event loop and potential browser optimizations, the order of execution for the two setTimeout callbacks with a delay of 0 milliseconds is not guaranteed to be consistent.

In this case, it might execute console.log('B'); before console.log('D');, leading to the output AE C B D.
Remember: The order of setTimeout callbacks with 0 delay is not strictly deterministic in JavaScript. However, Promises take precedence over setTimeout in the event loop, ensuring console.log('C'); executes before both setTimeout callbacks.

Top comments (0)