Course contentsShow
← Web Development
Lesson 2074 of 2,98238. JavaScript Performance in the BrowserFree lesson

Deferring Non-Critical Work

Using requestIdleCallback and setTimeout patterns to schedule low-priority work during idle periods.

Deferring Non-Critical Work

What you'll learn: How to use requestIdleCallback and setTimeout patterns to schedule low-priority tasks so they don't interfere with critical user interactions.

The Core Idea

Not all JavaScript tasks are equally urgent. Some work—like analytics tracking, logging, prefetching future content, or updating non-visible UI—can wait. By deferring this non-critical work until the browser has free time, you keep the main thread available for what matters most: responding to user input.

Think of it like a restaurant kitchen: during the dinner rush, chefs focus on orders. They don't reorganize the pantry or deep-clean equipment until things slow down. Similarly, defer non-essential JavaScript until the browser has idle moments.

Two Key Patterns

requestIdleCallback (preferred for truly optional work):

requestIdleCallback(() => {
  // Send analytics
  trackUserBehavior();
  
  // Prefetch next page
  prefetchResources();
}, { timeout: 2000 });

This runs your callback during idle periods. The timeout ensures it eventually runs even if the browser stays busy.

setTimeout with delay (for slightly deferred work):

setTimeout(() => {
  // Load secondary features
  initializeCommentSystem();
}, 100);

This pushes work to the end of the task queue, giving priority to immediate interactions.

When to Use Which

Use requestIdleCallback for work that can be delayed indefinitely (analytics, cleanup). Use setTimeout for work that should happen soon but not immediately (loading secondary UI components).

Key Takeaway: Defer non-critical JavaScript using requestIdleCallback for optional work during idle time and setTimeout to delay slightly less urgent tasks—keeping the main thread responsive for user interactions.