Skip to content

The Event Loop

JavaScript

Understand the event loop: call stack, callback queue, microtasks, and macrotasks.

Official Site
01

Overview

JS is single-threaded with an event loop. Call stack executes sync code. Task queue (macrotasks: setTimeout, I/O). Microtask queue (promises, queueMicrotask). Microtasks run before next macrotask. requestAnimationFrame runs before paint.

bash
console.log("1");
setTimeout(()=>console.log("4"),0);
Promise.resolve().then(()=>console.log("3"));
console.log("2");
// Output: 1 2 3 4
02

Best Practices

Microtasks (promises) run before macrotasks (setTimeout). Never block the event loop with sync work. Use requestAnimationFrame for visual updates. Use Web Workers for heavy computation. Use queueMicrotask for micro-scheduling.

Ready to try The Event Loop?

Visit the official site for the latest version and full documentation.

Visit The Event Loop