How does the Event Loop work?
The Event Loop is a fundamental concept in JavaScript that handles asynchronous operations and callback execution. It's what allows JavaScript to be non-blocking despite being single-threaded.
Key Components
- Call Stack - Executes synchronous code
- Web APIs - Handles async operations (setTimeout, fetch, etc.)
- Callback Queue - Stores callbacks ready for execution
- Microtask Queue - Higher priority queue for Promises
- Event Loop - Coordinates between these components
Example
console.log('Start');
setTimeout(() => {
console.log('Timeout 1');
}, 0);
Promise.resolve()
.then(() => console.log('Promise 1'));
setTimeout(() => {
console.log('Timeout 2');
}, 0);
console.log('End');
// Output:
// Start
// End
// Promise 1
// Timeout 1
// Timeout 2How It Works
- Synchronous code executes immediately on the call stack
- Async operations are delegated to Web APIs
- Completed async operations push callbacks to appropriate queues
- Event loop checks if call stack is empty
- If empty, processes microtasks first (Promises)
- Then processes macrotasks (setTimeout, setInterval)
Common Interview Follow-up Questions
- Why do microtasks have priority over macrotasks?
- How does this affect performance in web applications?
- What's the difference between setTimeout(fn, 0) and setImmediate()?
- How does the event loop differ in Node.js vs browsers?
Best Practices
- Avoid blocking the event loop with long-running tasks
- Use microtasks judiciously to prevent starving macrotasks
- Consider using Web Workers for CPU-intensive tasks
- Be aware of how different async operations are prioritized