Basics of Event Loop :-
I think before diving into the output, here's what you need to understand :-
JavaScript is single-threaded, but it can handle asynchronous operations via the event loop, which works with two primary queues:
- Macrotask Queue (also called Task Queue):
- Includes:
setTimeout
,setInterval
,setImmediate
, I/O, and others. - Scheduled after the current call stack and after all microtasks are cleared.
- Microtask Queue:
- Includes:
Promise.then()
,MutationObserver
, andqueueMicrotask()
. - Scheduled after the current call stack, but before any macrotasks.
The rule: After executing all synchronous code, JavaScript clears the entire microtask queue before processing the next macrotask.
Step-by-Step Breakdown of Your Code
✅Step 1: Initial Execution (Call Stack)
JavaScript reads the code from top to bottom and:
- Schedules two
setTimeout()
callbacks (macrotasks) → placed in the macrotask queue - Schedules two
Promise.then()
callbacks (microtasks) → placed in the microtask queue
console.log
statements are in callbacks.✅Step 2: Microtask Queue Execution
Once the synchronous code is done, the event loop clears the microtask queue first:
promise 1
is logged.promise 2
is logged.
Console after this step:
✅ Step 3: Macrotask Queue Execution
Now the event loop proceeds to the macrotask queue, in the order the tasks were scheduled:
timeout 1
is logged.timeout 2
is logged.
Console after this step:
✔ Final Answer:
C) promise 1
promise 2
timeout 1
timeout 2
This question appeared in the Capgemini 2nd round of interview, testing the candidate’s knowledge of Event Loop, setTimeout and Promise in JavaScript.