The Event Loop Deep Dive
JavaScript ka execution model: Call Stack (jaha current synchronous code chalता hai), Web APIs (browser ki async capabilities — setTimeout, fetch), Callback Queue/Task Queue (completed async operations ke callbacks yaha wait karte hain), Microtask Queue (Promises ke liye, HIGHER priority queue).
Event loop continuously check karta hai: "kya call stack khaali hai?" Agar haan, microtask queue se saara kaam pehle karo, PHIR task queue se ek kaam lo. Ye wajah hai ki Promises (microtasks) setTimeout (macrotask) se PEHLE chalte hain, chahe dono "ready" ho.
console.log("1: Sync");
setTimeout(() => console.log("2: setTimeout (macrotask)"), 0);
Promise.resolve().then(() => console.log("3: Promise (microtask)"));
console.log("4: Sync");
// Output order: 1, 4, 3, 2
// Sync code PEHLE (1, 4), phir microtasks (3 - Promise),
// PHIR macrotasks (2 - setTimeout) — chahe setTimeout ka delay 0 ho!- Call Stack = current sync execution, Web APIs = async operations handle karte hain
- Microtask Queue (Promises) = HIGHER priority than Task Queue (setTimeout)
- Event loop: stack khaali → microtasks saare → ek macrotask → repeat
requestAnimationFrame() ek special browser API hai jo callback ko browser ke NEXT REPAINT se pehle chalata hai — setTimeout() se better hai smooth animations ke liye, kyunki browser ke refresh rate se sync rehta hai.
function animate() {
// position update logic yaha
console.log("Frame render ho raha hai");
requestAnimationFrame(animate); // agla frame schedule karo
}
requestAnimationFrame(animate); // animation loop shuruNode.js mein process.nextTick() microtask queue se bhi PEHLE chalta hai (highest priority) — browser JavaScript mein directly available nahi hai, Node.js-specific concept, lekin event loop priority samajhne ke liye relevant hai.
// Node.js mein priority order (highest to lowest):
// 1. process.nextTick() callbacks
// 2. Promise microtasks
// 3. setTimeout/setInterval (macrotasks)
console.log("1: Sync");
setTimeout(() => console.log("4: setTimeout"), 0);
Promise.resolve().then(() => console.log("3: Promise"));
process.nextTick(() => console.log("2: nextTick"));
// Output: 1, 2, 3, 4