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)