Interview question
How does the event loop actually work step by step? Event loop असल में step by step कैसे काम करता है?
Answer
The event loop is the mechanism that continuously checks whether the call stack is empty, and if so, moves queued callbacks (microtasks first, then macrotasks) onto the stack for execution.
console.log('Script start');
setTimeout(() => {
console.log('setTimeout callback');
}, 0);
fetch('/api/data').then(() => {
console.log('Fetch resolved');
});
console.log('Script end');
// Step-by-step trace:
// 1. 'Script start' logged (sync, runs on call stack immediately)
// 2. setTimeout registers its callback with the Web API, timer starts (0ms)
// 3. fetch() starts a network request via Web API, returns a pending Promise
// 4. 'Script end' logged (sync)
// 5. Call stack is now empty - script's synchronous execution finished
// 6. Event loop checks: any microtasks pending? None yet from fetch (still pending)
// 7. Event loop checks macrotask queue: setTimeout's callback is ready (0ms elapsed)
// 8. setTimeout callback pushed to call stack, 'setTimeout callback' logged
// 9. Later, when fetch's network response arrives, the resolved Promise's
// .then() callback is queued as a MICROTASK
// 10. Event loop picks it up (microtasks have priority over remaining macrotasks)
// and 'Fetch resolved' is loggedThe core loop (simplified):
while (true) {
if (callStack.isEmpty()) {
while (microtaskQueue.hasTasks()) runNextMicrotask();
if (macrotaskQueue.hasTasks()) runNextMacrotask();
render(); // browser may repaint here
}
}
while (true) {
if (callStack.isEmpty()) {
while (microtaskQueue.hasTasks()) runNextMicrotask();
if (macrotaskQueue.hasTasks()) runNextMacrotask();
render(); // browser may repaint here
}
}
Event loop वो mechanism है जो लगातार check करता रहता है कि call stack खाली है या नहीं, और अगर खाली है तो queued callbacks (पहले microtasks, फिर macrotasks) को stack पर execution के लिए भेजता है।
console.log('Script start');
setTimeout(() => {
console.log('setTimeout callback');
}, 0);
fetch('/api/data').then(() => {
console.log('Fetch resolved');
});
console.log('Script end');
// Step-by-step trace:
// 1. 'Script start' log होता है (sync)
// 2. setTimeout callback Web API के साथ register होता है, timer शुरू
// 3. fetch() Web API के ज़रिए network request शुरू करता है
// 4. 'Script end' log होता है (sync)
// 5. Call stack अब खाली - sync execution खत्म
// 6. Event loop microtasks check करता है: fetch का अभी कोई नहीं (pending)
// 7. Macrotask queue check: setTimeout callback ready है
// 8. setTimeout callback stack पर push, log होता है
// 9. बाद में fetch response आने पर .then() callback MICROTASK बनता है
// 10. Event loop इसे उठाता है (microtasks को priority है) और log करता हैCore loop (simplified):
while (true) {
if (callStack खाली है) {
जब तक microtasks हों, चलाओ;
अगला macrotask चलाओ;
render();
}
}
while (true) {
if (callStack खाली है) {
जब तक microtasks हों, चलाओ;
अगला macrotask चलाओ;
render();
}
}
Was this answer clear?