JavaScript Me Event Loop & Microtask Queue Kya Hote Hai
Samjhein ki JavaScript ek saath itne saare tasks kaise handle kar leta hai.
The Big Question: JavaScript Single-Threaded hai, fir Asynchronous kaise?
JavaScript ek single-threaded, synchronous language hai. Iska matlab hai ki woh ek samay par ek hi kaam kar sakta hai, line by line. Lekin jab hum web applications use karte hain, toh hum dekhte hain ki API calls, timers, aur UI updates jaise kai kaam ek saath hote hue dikhte hain.
Yeh possible hota hai Event Loop, Call Stack, aur Queues (Macrotask aur Microtask) ke combination se.
1. Call Stack
Call Stack ek LIFO (Last-In, First-Out) data structure hai jo track karta hai ki kaunsa function abhi run ho raha hai. Jab aap ek function call karte hain, toh woh stack ke top par add hota hai, aur jab complete ho jaata hai, toh wahan se remove (pop) ho jaata hai.
function first() {
console.log("First function");
second();
}
function second() {
console.log("Second function");
}
first();
2. Event Loop
Event Loop ko aap ek traffic police samajh sakte hain. Iska kaam hai continuously check karna ki Call Stack khali hai ya nahi. Agar Call Stack khali hai, toh woh Queues se pending tasks ko execute hone ke liye Call Stack me bhej deta hai.
3. Macrotask (Task) Queue
Yeh ek FIFO (First-In, First-Out) queue hai jismein bade asynchronous tasks ke callbacks rakhe jaate hain.
setTimeout
&setInterval
- DOM events (click, keypress)
- I/O operations (API calls)
console.log("Start");
setTimeout(() => { console.log("Timeout done"); }, 0);
console.log("End");
// Output: Start, End, Timeout done
4. Microtask Queue (VIP Queue)
Microtask Queue ki priority Macrotask Queue se zyada hoti hai. Jab bhi Call Stack khali hota hai, Event Loop hamesha pehle poori Microtask Queue ko khali karta hai, uske baad hi Macrotask Queue se ek task leta hai.
- Promises (
.then()
,.catch()
,.finally()
) MutationObserver
process.nextTick()
(Node.js)
Execution Order Example
console.log("Start");
setTimeout(() => { console.log("Timeout (Macrotask)"); }, 0);
Promise.resolve().then(() => { console.log("Promise (Microtask)"); });
console.log("End");
// Output:
// Start
// End
// Promise (Microtask)
// Timeout (Macrotask)
Explanation: "Start" aur "End" synchronous hain, isliye pehle chalenge. Fir Event Loop Microtask (Promise) ko pehle chalayega, aur uske baad Macrotask (setTimeout) ko.
Key Takeaways
- JavaScript single-threaded hai, lekin Event Loop ki wajah se non-blocking (asynchronous) hai.
- Call Stack synchronous code execute karta hai.
- Event Loop Call Stack aur Queues ko manage karta hai.
- Microtask Queue (Promises) ki priority Macrotask Queue (setTimeout) se zyada hoti hai.
Apni knowledge test karne ke liye is quick quiz ko dein.
Start Quiz