wasAsked.

What is the event loop in JavaScript?

Frequently Asked (All Companies) · Role not specified · technical

Published

Year not specified · JavaScript

Community answers

Posted by wasAsked editorial collection

JavaScript runs your code on a single main thread. The event loop is the mechanism that lets it handle asynchronous work — timers, network requests, user events — without blocking that thread. It continuously coordinates the call stack and task queues. Main components 1. Call stack: where function calls execute, one at a time. Synchronous code runs here until the stack is empty. 2. Web APIs or Node.js APIs: the browser or Node.js runtime handles asynchronous operations (timers, fetch, DOM events, file I/O) outside the JavaScript thread. 3. Task queue (macrotask queue): callbacks from setTimeout, setInterval, I/O and UI events wait here. 4. Microtask queue: promise callbacks (then, catch, finally, code after await), queueMicrotask and MutationObserver callbacks. 5. The event loop: whenever the call stack is empty, it runs all microtasks, then takes the next macrotask, and repeats. In browsers, rendering (style, layout, paint) typically happens between tasks when needed. Key rule: after each macrotask (and after the initial script), the microtask queue is completely drained before the next macrotask runs. Classic example console.log('1: start'); setTimeout(() => console.log('2: timeout'), 0); Promise.resolve().then(() => console.log('3: promise')); console.log('4: end'); Output: 1: start 4: end 3: promise 2: timeout Why: synchronous logs run first; the promise callback is a microtask, so it runs as soon as the stack is empty; the setTimeout callback is a macrotask, so it waits until microtasks are done — even with a 0 ms delay. Async/await in the event loop async function load() { console.log('A'); await fetch('/api/data'); // the function pauses; the rest becomes a microtask when the promise settles console.log('C'); } load(); console.log('B'); // A, B, then C after the response arrives Node.js specifics - Node's event loop (libuv) has phases: timers, pending callbacks, poll (I/O), check (setImmediate), close callbacks. - process.nextTick callbacks run before other microtasks, then promise microtasks. - setImmediate runs in the check phase after I/O; its ordering relative to setTimeout(fn, 0) can vary when called from the main module. Why it matters - Blocking the main thread freezes the UI or stalls a Node.js server: while (Date.now() < start + 5000) {} // blocks everything for 5 seconds Long-running CPU work should be split into chunks, moved to Web Workers or worker threads, or handled by another service. - Infinite or very long microtask chains can starve rendering and macrotasks. - Understanding ordering helps debug race conditions and unexpected output in tests and UI updates. - setTimeout delays are minimums, not guarantees; nested timers are clamped (about 4 ms) and inactive tabs may throttle timers. Interview summary: "JavaScript executes on a single call stack. Asynchronous operations are handled by the runtime and their callbacks are queued. The event loop runs all microtasks (promises) after each task, then the next macrotask (timers, I/O, events), which is why promise callbacks run before setTimeout callbacks."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics