JavaScript Notes
Master JavaScript
Introduction
The event loop is the heart of JavaScript's concurrency model. It's the mechanism that allows JavaScript — despite being single-threaded — to handle asynchronous operations, respond to user events, make network requests, and run timers, all without blocking.
Understanding the event loop answers questions like:
- Why does
setTimeout(fn, 0)run after synchronous code? - Why do Promises run before
setTimeout? - How can JavaScript be "single-threaded" yet handle multiple things?
- What does "non-blocking" actually mean?
The Complete JavaScript Runtime Picture
The Event Loop Algorithm — Step by Step
The event loop follows a precise order in every "tick" (cycle):
The Classic Demo — Understanding Execution Order
A D C B
Why this order? Step-by-step:
Advanced Execution Order Example
1. sync start 2. sync end 3. microtask 1 4. microtask 2 5. queueMicrotask 6. setTimeout 0ms 7. micro inside macro 8. setTimeout 100ms
Execution trace:
Microtask Queue — The VIP Lane
Microtasks always run before the next macrotask. This is crucial for Promises:
Sync Microtask 1 Microtask 2 (chained) Microtask 3 (chained) Macrotask: setTimeout
Sources that add to the microtask queue:
Promise.then()/.catch()/.finally()queueMicrotask(fn)MutationObservercallbacksawaitexpression resumptions (inside async functions)
The Danger: Infinite Microtasks (Starvation)
// ❌ DANGEROUS: This starves macrotasks and the render loop!
function addInfiniteMicrotasks() {
Promise.resolve().then(addInfiniteMicrotasks); // Keeps creating new microtasks
}
addInfiniteMicrotasks();
// setTimeout callbacks and browser painting will NEVER runThe event loop always drains ALL microtasks before each macrotask. If microtasks are continuously generated, the render loop and all setTimeout callbacks are permanently blocked.
Node.js Event Loop — Additional Phases
Node.js has a more detailed event loop with specific phases:
Practical Impact: Never Block the Event Loop
Common Mistakes ⚠️
Mistake 1: Assuming setTimeout(fn, 0) Runs Before Promises
This is second This is first
Mistake 2: Blocking the Main Thread
// ❌ This freezes the browser — no events, no rendering, no async
function blockingOperation() {
const deadline = Date.now() + 5000; // 5 seconds
while (Date.now() < deadline) {} // Busy wait — TERRIBLE!
}
blockingOperation();
// During these 5 seconds: no clicks work, page can't render, no callbacks runMistake 3: Expecting Nested Microtask Order
1 2 3
Interview Questions 🎯
Q1. What is the JavaScript event loop?
The event loop is the mechanism that coordinates the JavaScript call stack, Web APIs, and task queues. It continuously checks: when the call stack is empty, it drains all microtasks from the microtask queue, then picks one macrotask from the callback queue and pushes it to the stack. This cycle repeats indefinitely, enabling non-blocking async programming in a single-threaded environment.
Q2. What is the execution order: sync code, setTimeout, Promise?
1. Synchronous code runs first (call stack). 2. Promise callbacks (microtasks) run next — all of them, in order. 3. setTimeout callbacks (macrotasks) run last. So: sync → microtasks → setTimeout.
Q3. What's the difference between microtask and macrotask queues?
Microtask queue: contains Promise callbacks and queueMicrotask(). All microtasks are processed completely after each synchronous task and before the next macrotask. Macrotask queue (callback queue): contains setTimeout, setInterval, I/O callbacks. Only one macrotask is processed per event loop cycle.Q4. Can JavaScript truly be "non-blocking" if it's single-threaded?
Yes, through delegation. Long-running operations (network requests, timers, file I/O) are handed off to Web APIs (in the browser) or libuv (in Node.js), which run on separate threads. When complete, they place callbacks in the queue. JavaScript itself never blocks — it just processes callbacks when the stack is free.
Q5. What happens if microtasks keep creating more microtasks?
Macrotasks are starved (never run), and browser rendering is blocked. This is called "microtask starvation." The event loop drains ALL microtasks before each macrotask, so infinite microtask generation prevents any macrotask or render from ever executing.
Q6. Why is requestAnimationFrame better than setTimeout for animations?
requestAnimationFramecallbacks are synchronized with the browser's render cycle (~16ms for 60fps). They run at the optimal time just before the browser paints a frame.setTimeoutwith 16ms can drift or fire at wrong times relative to the render cycle, causing janky animations.
Q7. How does await interact with the event loop?
When a function hitsawait, it suspends (returns control to the caller) and the awaited Promise's resolution callback is added to the microtask queue. When the stack is empty and the Promise resolves, the microtask queue resumes the async function. This means code afterawaitruns as a microtask, not synchronously.
Q8. What is queueMicrotask() used for?
queueMicrotask(fn) directly schedules a function as a microtask without creating a Promise. It's useful when you want guaranteed microtask-level priority (runs before any macrotask, after all sync code) without the overhead of creating a Promise object.Key Takeaways 📌
- The event loop is a continuous cycle coordinating stack, Web APIs, and queues
- Synchronous code always runs first — nothing interrupts it
- Microtasks (Promises) run before every macrotask — they drain completely
- Macrotasks (setTimeout): only ONE per event loop cycle
- Web APIs are the browser's async infrastructure — not part of JS engine
- Blocking the main thread with heavy sync work freezes everything
- The event loop only moves work to the stack when it's completely empty
- Understanding this model is fundamental to writing correct async JavaScript
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Event Loop - Complete Guide with Visual Diagrams & Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, asynchronous, event, loop
Related JavaScript Master Course Topics