Event Loop
The Event Loop is a mechanism in JavaScript that allows non-blocking, asynchronous execution even though JavaScript is single-threaded.
In simple terms:
The Event Loop decides when and how JavaScript executes asynchronous code.
Why JavaScript Needs the Event Loop
- JavaScript runs on a single thread, which means:
- Only one task can execute at a time
Long operations would block the entire program
The Event Loop helps by:
Handling async operations
Preventing blocking
Keeping applications responsive
JavaScript Execution Model
JavaScript works using these main components:
- Call Stack
- Web APIs
- Callback Queue
- Microtask Queue
- Event Loop
1. Call Stack
The Call Stack keeps track of functions being executed.
Example
function first() { console.log("First");}
function second() { console.log("Second");}
first();second();Output
FirstSecondExecutes one function at a time
Uses LIFO (Last In, First Out)
2. Web APIs
Web APIs are provided by the browser (not JavaScript itself).
Examples:
- setTimeout
- fetch
- DOM events
setTimeout(() => { console.log("Hello");}, 2000);The timer runs in Web APIs, not in the Call Stack.
3. Callback Queue (Task Queue)
When an async task completes:
- Its callback is placed in the Callback Queue
- It waits until the Call Stack is empty
4. Microtask Queue
Microtasks have higher priority than callbacks.
Microtasks include:
- Promises (then, catch)
- queueMicrotask
5. Event Loop
The Event Loop continuously checks:
- Is the Call Stack empty?
- If yes, execute Microtasks first
- Then move to Callback Queue
Complete Execution
console.log("Start");
setTimeout(() => { console.log("Timeout");}, 0);
Promise.resolve().then(() => { console.log("Promise");});
console.log("End");Execution Order
- Start - Call Stack
- End - Call Stack
- Promise - Microtask Queue
- Timeout - Callback Queue
Output
StartEndPromiseTimeoutEvent Loop Flow (Step-by-Step)
- Execute synchronous code
- Send async tasks to Web APIs
- Push Promise callbacks to Microtask Queue
- Push timers/events to Callback Queue
- Event Loop moves tasks when stack is empty
Difference Between Microtask and Callback Queue
| Feature | Microtask Queue | Callback Queue |
|---|---|---|
| Priority | Higher | Lower |
| Examples | Promises | setTimeout |
| Execution | First | After microtasks |
Why Promises Execute Before setTimeout
Because:
- Promises use Microtask Queue
- setTimeout uses Callback Queue
Event Loop always processes Microtasks first.
Real-World Importance of Event Loop
- Smooth UI interactions
- Efficient API calls
- Non-blocking applications
- Better performance optimization
Two Minute Drill
- Event Loop manages async execution
- Call Stack executes sync code
- Web APIs handle async tasks
- Microtask Queue runs before Callback Queue
- Promises execute before setTimeout
- Event Loop keeps apps responsive
Need more clarification?
Drop us an email at career@quipoinfotech.com
