Tech Interview RoomStudy guides

JavaScript

Explain the event loop, the call stack, microtasks and macrotasks.

Intermediate · 2 min read · Lesson 5 of 12 in JavaScript

JavaScript runs on one thread with one call stack. Asynchronous work is handed to the host (the browser or Node.js), and the event loop decides when callbacks come back.

The pieces

  • Call stack: the functions currently executing.
  • Web APIs / host APIs: timers, network, DOM events. They run outside the stack.
  • Macrotask (task) queue: setTimeout, setInterval, I/O, UI events, MessageChannel.
  • Microtask queue: promise callbacks (then, catch, finally, code after await), queueMicrotask, MutationObserver.

The loop

  1. Run one macrotask (the initial script counts as the first).
  2. When the stack is empty, drain all microtasks, including ones added while draining.
  3. The browser may render (style, layout, paint), running requestAnimationFrame callbacks just before.
  4. Take the next macrotask.

Because microtasks drain completely, an endless chain of promises can starve rendering, just like a long while loop.

Example

js
console.log('1 script start');
setTimeout(() => console.log('6 timeout'), 0);
Promise.resolve()
  .then(() => console.log('3 micro 1'))
  .then(() => console.log('5 micro 2'));
queueMicrotask(() => console.log('4 queueMicrotask'));
console.log('2 script end');

Output order: 1, 2, 3, 4, 5, 6. The script is the current macrotask, then microtasks drain (micro 2 is queued while micro 1 runs, and still runs before the timeout), then the timer callback runs as the next macrotask.

Follow-up questions interviewers ask

Try answering each one before you open it.

Why is setTimeout(fn, 0) not really 0 ms?

It only queues a macrotask, which waits for the current script and all microtasks to finish, and possibly a render. Browsers also clamp nested timers (after 5 levels) to at least 4 ms, and background tabs throttle timers to 1 s or more. Use queueMicrotask to run right after the current code, or requestAnimationFrame for visual updates.

How do you keep the UI responsive during heavy computation?

Split the work into chunks and yield between them (await scheduler.yield() where supported, or setTimeout), move it to a Web Worker, or use requestIdleCallback for low-priority work. Long tasks over 50 ms hurt Interaction to Next Paint (INP).