intermediate

Event loop

Call stack, tasks, microtasks, Promises, async/await, and observable ordering.

The call stack runs synchronously until empty. Promise reactions enqueue microtasks; timers and many I/O callbacks enqueue macrotasks. After each macrotask, the runtime drains all microtasks before the next macrotask.

					console.log('sync');
setTimeout(() => console.log('task'), 0);
Promise.resolve().then(() => console.log('microtask'));
// sync → microtask → task
				

`setTimeout(..., 0)` is not immediate — it schedules a task. Long microtask chains can delay rendering and timers.

On interviews, explain the concept with a concrete example and name the runtime behavior interviewers probe.

Common pitfalls include mixing similar APIs and forgetting edge cases during live coding.

The trade-off is often clarity versus performance or safety versus convenience.

Checklist:

  • Synchronous code runs first.
  • Promises schedule microtasks.
  • Timers schedule macrotasks.
  • Drain microtasks between macrotasks.