🧠 Why This Topic?
Have you ever wondered…
- How does JavaScript run code line by line but still handle things like API calls, timers, and click events without blocking everything?
- That’s where the Event Loop comes in.
- This is one of the most misunderstood but most important concepts for every JavaScript developer — especially when working with asynchronous code.
Let’s break it down in the simplest way possible.
🧵 JavaScript Is Single-Threaded
JavaScript can do one thing at a time.
- That means it has one call stack (as we learned on Day 1).
- But we often deal with tasks that take time, like:
- Fetching from an API
- Reading files
- Timers (setTimeout)
- User events (like clicking a button)
So how does JavaScript handle these without freezing the page?
🛠️ Meet the Event Loop
Here’s the key idea:
JavaScript’s runtime environment (like the browser or Node.js) uses Web APIs, a Callback Queue, and an Event Loop to manage asynchronous code.
🌀 Event Loop Flow:
- Call Stack runs synchronous code.
- When an async function (e.g., setTimeout) is hit:
- It’s passed to the Web API.
- When done, the callback is sent to the Callback Queue.
- Event Loop checks:
- Is the Call Stack empty?
- If yes, it pushes the next item from the Callback Queue to the stack.
🔧 Visualizing with Example
Output:
🔄 Microtasks vs Macrotasks
Let’s compare:
✅ Summary: Event Loop in 5 Points
- JavaScript runs one task at a time (single-threaded).
- Long or async tasks (like timers, fetch) are passed to Web APIs.
- When ready, the results go to the Callback Queue.
- The Event Loop pushes tasks from the queue only if the call stack is empty.
- Microtasks (Promises) have higher priority than macrotasks.
✍️ Written By
Chaitanya Chopde
🌟 Inspired By
@devsyncin
Top comments (0)