Understanding the JavaScript Event Loop & Asynchronous Execution
Understand how single-threaded JavaScript handles asynchronous operations: Call Stack, Web APIs, Microtask queue (Promises), and Macrotask queue (setTimeout).
console.log("1: Synchronous start");
setTimeout(() => {
console.log("4: Macrotask callback (setTimeout)");
}, 0);
Promise.resolve().then(() => {
console.log("3: Microtask callback (Promise)");
});
console.log("2: Synchronous end");
// Output Order:
// 1: Synchronous start
// 2: Synchronous end
// 3: Microtask callback (Promise)
// 4: Macrotask callback (setTimeout)
1. The Single-Threaded Nature of JavaScript
JavaScript has a single call stack and executes one command at a time. It delegates long-running tasks like timers, network requests, and DOM events to browser Web APIs.
2. Microtasks vs. Macrotasks
When an asynchronous operation finishes, its callback enters one of two queues:
- Microtask Queue: Holds Promise callbacks (
.then,async/await) and MutationObservers. - Macrotask (Task) Queue: Holds callbacks from
setTimeout,setInterval, and I/O events.
Crucially, the Event Loop drains the entire Microtask queue before moving on to the next Macrotask.
- Promises always resolve before setTimeout callbacks even with a 0ms delay.
- Heavy computational loops block the Call Stack and freeze the browser UI.
- Use Web Workers for heavy CPU-bound processing without degrading UI responsiveness.
Frequently Asked Questions
Why does setTimeout(fn, 0) not run immediately?
Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.
Explore Related Course Call 7503962162