JavaScript - Microtasks & Event Loop

Overview

Estimated time: 20–30 minutes

The event loop coordinates JavaScript's single-threaded execution with asynchronous tasks. Microtasks (promises, mutation observers) and macrotasks (timers, I/O) are handled in different phases.

Learning Objectives

  • Understand the event loop and task queues.
  • Distinguish between microtasks and macrotasks.

Prerequisites

Event Loop Phases

  • Macrotasks: setTimeout, setInterval, I/O, UI events
  • Microtasks: Promises, MutationObserver

Example

console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('end');
// Output: start, end, promise, timeout

Common Pitfalls

  • Assuming setTimeout(..., 0) runs immediately (microtasks run first).
  • Blocking the event loop with long-running code freezes the UI.

Summary

Understanding the event loop and task queues is key to writing responsive JavaScript apps.