The Event Loop in JavaScript
As you probably know JavaScript is single-threaded, which means it can only do ONE thing at a time.
Then how is every execution handled?
How does it:
• Wait for 5 seconds without blocking the UI?
• Load data from the internet while still responding to user input?
• Keep animations running while processing events?
If you’ve ever wondered how JavaScript handles multiple tasks like fetching data, showing alerts, and waiting for timers all without freezing your app the answer lies in something called the Event Loop.
Let’s explore what Event Loop is, why it’s important, how it works, and how different tasks like setTimeout
, setInterval
, Promise
, and Observable
etc. fit into the picture.
What Is the Event Loop?
Think of the Event Loop as a watchdog.
It continuously checks:
“Is the call stack empty?
If yes, let’s move tasks from the queue to the stack.”
It prioritizes microtasks before macrotasks as discussed above.
How the Event Loop Works :
Here’s the basic flow:
1. JavaScript has a Call Stack (LIFO — Last In First Out) where it executes your code.
2. There’s a Task Queue (Callback queue, like setTimeout
) and a Microtask Queue (Priority queue, like Promise.then()
).
3. The Event Loop checks if the Call Stack is empty.
• If yes, it pushes tasks from the queue (first microtasks, then tasks) to the stack.
4. The stack runs the task, clears it, then goes back to the queue.
Types of Tasks and Their Priorities
Macro Tasks (Regular Tasks)
• Handled after microtasks.
• Examples: setTimeout
, setInterval
, setImmediate
, DOM events.
Micro Tasks (High Priority)
• Handled immediately after the current task and before any macro tasks.
• Examples: Promise.then()
, queueMicrotask
, MutationObserver
.
Code Examples
console.log(“Start”);
setTimeout(() => {
console.log(“Inside setTimeout”);
}, 0);
Promise.resolve().then(() => {
console.log("Inside Promise");
});
console.log(“End”);
Output :
Start
End
Inside Promise
Inside setTimeout
Real-Life Example: The Burger Chef
Imagine a chef (JavaScript engine):
- He cooks one order at a time (single-threaded).
- There’s a VIP tray (microtask queue) and a normal tray (macrotask queue).
- The chef always finishes VIP orders before touching regular ones.
Conclusion
JavaScript is single-threaded but handles async tasks using the Event Loop.
Microtasks (Promises) run before macrotasks (setTimeout).
Event Loop checks the call stack, then the microtask queue, then macrotasks.
Happy Coding!!!
—
Hope this helps.
Cheers!!
Sangwin Gawande
About me : https://sangw.in