Skip to content
javascript questions

JavaScript · 2 of 10middle~1 min

How does the event loop work in JavaScript?

#async#core

Event Loop

JavaScript is single-threaded - it can only do one thing at a time. The event loop is the mechanism that handles asynchronous operations.

Components

text
┌─────────────────────────────────┐ │ Call Stack │ <- executes synchronous code ├─────────────────────────────────┤ │ Microtask Queue │ <- Promise callbacks, queueMicrotask ├─────────────────────────────────┤ │ Macrotask Queue │ <- setTimeout, setInterval, I/O └─────────────────────────────────┘

Order of execution

  1. Run all synchronous code (call stack).
  2. Run all microtasks (Promise .then, queueMicrotask).
  3. Run one macrotask (setTimeout, setInterval).
  4. Repeat from step 2.

Example

js
console.log('1 - sync'); setTimeout(() => console.log('2 - macrotask'), 0); Promise.resolve().then(() => console.log('3 - microtask')); console.log('4 - sync'); // Output: // 1 - sync // 4 - sync // 3 - microtask // 2 - macrotask

Why microtasks come first

js
Promise.resolve() .then(() => console.log('micro 1')) .then(() => console.log('micro 2')); setTimeout(() => console.log('macro'), 0); // micro 1 -> micro 2 -> macro // ALL microtasks drain before any macrotask runs

Understanding the event loop is critical for debugging timing bugs, infinite loops in Promises, and understanding why setTimeout(fn, 0) doesn't mean "run immediately".

updated

did you know it?

related questions