Vibeshnan Kanagamani
Learn With Vibe
Javascript Event Loop
How JS handles async behind the scenes
[Link]
What is the Javascript Event Loop ?
Ever wondered why Javascript can do multiple things at
once, even though it’s single threaded ?
The answer is the Event Loop, one of the most misunderstood yet
crucial mechanisms in JavaScript. Let's break it down.
Javscript runs on a single thread, meaning it can only do one thing
at a time.
But real app need to handle timers, network calls, user events all
withouth Freezing UI
Event Loop is the mechanism that makes it possible. It
continuosly monitors the Call Stack and the Task Queues, pushing
callbacks onto the stack when it's empty
The Golden Rule
JavaScript executes synchronous code first, then processes
microtasks, then macrotasks ⟶ repeat forever.
[Link]
The Runtime Architechture
The JS runtime is made of four key parts:
• Call Stack – LIFO structure tracking function execution
• Web APIs – browser-provided async capabilities (setTimeout, fetch,
DOM)
• Microtask Queue – high-priority queue (Promises, queueMicrotask)
• Macrotask Queue – lower-priority queue (setTimeout, setInterval, I/O)
[Link]
Execution Order
What does this code print ?
Answer : 1 →4→3→2
Sync code runs first (1, 4).
Then microtasks (3).
Then macrotasks (2).
Microtasks ALWAYS drain completely before any macrotask runs
[Link]
Vibeshnan kanagamani
SAVE THIS POST
AS A REMINDER
AND SHARE
[Link]