JavaScript Event Loop Explained in Simple Words
JavaScript is single-threaded.
That means it can do one task at a time.
But then a question comes…
If JavaScript runs one thing at a time,
how does it handle:
- setTimeout
- API calls
- Promises
- async/await
👉 The answer is Event Loop.
🧠 First, Understand This
JavaScript runtime has 4 important parts:
- Call Stack – where code runs
- Web APIs – handles timers, fetch, DOM events
- Callback Queue – waiting area for async tasks
- Event Loop – the manager
🍽 Real-Life Example (Very Simple)
Imagine a restaurant with only one chef 👨🍳
Two customers order:
- Tea (fast)
- Biryani (takes time)
The chef:
- Starts cooking biryani
- Serves tea meanwhile
- When biryani is ready → serves it
The chef does not stand waiting.
That smart system = Event Loop
⚙️ How Event Loop Works
Step 1: Code runs in the Call Stack
Step 2: Async tasks (like setTimeout) go to Web APIs
Step 3: After completion, they move to Callback Queue
Step 4: Event Loop keeps checking:
“Is the Call Stack empty?”
If YES →
It pushes the task from Queue → into Stack → executes it.
💻 Example Code
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
console.log("End");
Output:
Start
End
Timeout
🤔 Why Does This Happen?
Even though delay is 0:
- setTimeout goes to Web API first
- Then to Callback Queue
- Event Loop waits until Stack is empty
- Then executes it
That’s why "End" prints before "Timeout".
🎯 Important Interview Point
JavaScript is:
- Single-threaded
- But asynchronous
- Because of the Event Loop
If someone asks:
“How does JavaScript handle async code?”
Now you can explain it clearly and confidently.
Top comments (0)