🔥 Event Loop trap: If you miss this output, async JS will bite you in production 😅 ❓What’s the output order? A) A E G C D F B B) A G E C D F B C) A E G B C D F D) A E C D F G B 💬 Drop your answers + reasoning 👇 #CodeSnatch #javascript #eventloop #asyncawait #interviewprep #webdevelopment
The answer is A, and here way using ticket sales as an example. The Priority Hierarchy The Call Stack (Synchronous): These are the people already at the gate with "First Class" tickets. They go first, no matter what (A, E, G). The Microtask Queue: These are "Priority Boarding" passengers. The gate agent (the Event Loop) must empty this entire line before looking at anyone else (C, D, F). The Macrotask Queue (Callback Queue): These are "General Boarding." Even if you were the very first person to arrive at the airport (setTimeout with 0ms), you have to wait for every single person in Priority Boarding to get on the plane first (B). Why setTimeout(..., 0) is never truly 0 Even with a delay of 0, the browser or Node.js environment has to: Recognize the timer has expired. Move the callback to the Macrotask queue. Wait for the Event Loop to finish the current "tick" (which includes clearing that entire Microtask queue). Because Promise.then, queueMicrotask, and the code following an await all live in that "Priority" Microtask queue, they will always jump ahead of your setTimeout.
💡Tip --> You should understand the difference between Micro and Macro tasks! Microtasks: Promise.resolve().then(...) queueMicrotask(...) code after await (the continuation) Macrotasks: setTimeout(..., 0)
Step-by-step: Synchronous (runs immediately): console.log("A") → A async IIFE starts → console.log("E") → E hits await null → schedules the continuation ("F") as a microtask console.log("G") → G Microtasks (run after sync code, before timers): 5. Promise.then → C 6. queueMicrotask → D 7. async continuation after await → F Macrotasks / timers (next tick): 8. setTimeout(..., 0) → B