Understanding JavaScript Asynchronous Execution: How the Event Loop, Microtasks, and Macrotasks callbacks Work with Promises and setTimeout Examples

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:

  1. Macrotask Queue (also called Task Queue):
    • Includes: setTimeoutsetIntervalsetImmediate, I/O, and others.
    • Scheduled after the current call stack and after all microtasks are cleared.
  2. Microtask Queue:
    • Includes: Promise.then(), MutationObserver, and queueMicrotask().
    • 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

setTimeout(() => {
console.log('timeout 1'); }, 0); Promise.resolve().then(() => { console.log("promise 1"); }); setTimeout(() => { console.log('timeout 2'); }, 0); Promise.resolve().then(() => { console.log("promise 2"); });

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
No logs are printed at this point because all the 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:

  1. promise 1 is logged.
  2. promise 2 is logged.

Console after this step:

promise 1
promise 2

Step 3: Macrotask Queue Execution

Now the event loop proceeds to the macrotask queue, in the order the tasks were scheduled:

  1. timeout 1 is logged.
  2. timeout 2 is logged.

Console after this step:

promise 1
promise 2
timeout 1
timeout 2

✔ 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.

Post a Comment

Previous Post Next Post