Course contentsShow
← JavaScript
Lesson 1212 of 2,72327. The Event LoopFree lesson

When to Use setTimeout vs Alternatives

Know when setTimeout is appropriate versus requestAnimationFrame, queueMicrotask, or async/await patterns.

When to Use setTimeout vs Alternatives

You'll learn when setTimeout is the right tool versus requestAnimationFrame, queueMicrotask, or async/await patterns.

The Core Question

JavaScript offers several ways to schedule asynchronous work, but they're optimized for different purposes. Choosing the wrong one can hurt performance or create subtle bugs.

Use setTimeout When...

setTimeout is best for general-purpose delays where precise timing isn't critical:

  • Debouncing user input (waiting for typing to stop)
  • Polling at intervals (checking server status every few seconds)
  • Delaying non-urgent work (showing a notification after 3 seconds)
  • Implementing timeouts (aborting an operation if it takes too long)

Use requestAnimationFrame When...

For visual updates synchronized with screen redraws (typically 60fps):

  • Animations and transitions
  • Updating canvas or game graphics
  • Measuring layout changes smoothly

Why? It runs before the browser paints, preventing visual jank. setTimeout can't guarantee this timing.

Use queueMicrotask When...

For immediate execution after current code, but before any setTimeout/DOM updates:

  • Breaking up long synchronous tasks
  • Coordination between promise-based systems
  • Ensuring code runs before the next event loop task

Use Async/Await When...

For promise-based asynchronous flows where you need readable sequential logic:

  • Fetching data from APIs
  • Reading files or databases
  • Chaining dependent async operations

Unlike setTimeout, async/await handles promise resolution naturally without manual delay management.

The Analogy

Think of setTimeout as mailing a letter (arrives eventually), requestAnimationFrame as syncing dance moves to music beats (precise rhythm), queueMicrotask as whispering to someone immediately after you finish your sentence, and async/await as following a recipe step-by-step where each step might take time.

Key Takeaway: Use setTimeout for delays, requestAnimationFrame for visuals, queueMicrotask for immediate microtask scheduling, and async/await for promise-based logic flows.