JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext
javascript
mid
runtime

Explain the JavaScript Event Loop and how it handles asynchronous operations.

event-loop
async
runtime
microtasks
macrotasks
performance
Quick Answer

The Event Loop is JavaScript's mechanism for handling asynchronous operations. It continuously checks the call stack and task queues, executing callbacks from the microtask queue (Promises) before the macrotask queue (setTimeout, events).

Detailed Explanation

JavaScript is single-threaded but handles async operations through the Event Loop.

Key Components:

  1. Call Stack: Executes synchronous code, one frame at a time

  2. Web APIs / Node APIs: Handle async operations (timers, fetch, I/O)

  3. Task Queue (Macrotasks):

    • setTimeout, setInterval, setImmediate
    • I/O operations, UI rendering
    • Event callbacks
  4. Microtask Queue:

    • Promise callbacks (.then, .catch, .finally)
    • queueMicrotask()
    • MutationObserver

Execution Order:

  1. Execute all synchronous code in call stack
  2. Call stack empty → Process ALL microtasks
  3. Process ONE macrotask
  4. Process ALL microtasks again
  5. Repeat from step 3

Code Examples

Event Loop execution order
console.log('1: Start');

setTimeout(() => {
  console.log('2: setTimeout');
}, 0);

Promise.resolve()
  .then(() => console.log('3: Promise 1'))
  .then(() => console.log('4: Promise 2'));

console.log('5: End');

// Output order:
// 1: Start
// 5: End
// 3: Promise 1
// 4: Promise 2
// 2: setTimeout

// Explanation:
// - Sync code runs first (1, 5)
// - Microtasks (Promises) run before macrotasks
// - setTimeout is a macrotask, runs last

Resources

MDN - Event Loop

docs

JavaScript Visualized: Event Loop

video

JavaScript.info - Event Loop

article

Related Questions

What are Promises in JavaScript and how do they work?

mid
async
Previous
How do async/await work and how do they relate to Promises?
Next
How does the 'this' keyword work in JavaScript?