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

Timeout Option for Guaranteed Execution

Learn to use the timeout option to ensure tasks eventually run even when the browser stays busy.

Timeout Option for Guaranteed Execution

What you'll learn: How to use the timeout option in requestIdleCallback to ensure critical tasks run even when the browser never becomes idle.

The Problem with Pure Idle Callbacks

You've learned that requestIdleCallback runs tasks during browser idle time. But what if the browser never becomes idle? On a busy page with constant animations, scrolling, or user interactions, your callback might wait indefinitely. This is dangerous for tasks that eventually must run—like analytics, data syncing, or cleanup operations.

The timeout Option to the Rescue

The requestIdleCallback API accepts a second parameter: an options object with a timeout property. This value (in milliseconds) acts as a safety net:

requestIdleCallback((deadline) => {
  // Perform non-critical work
  processAnalytics();
}, { timeout: 2000 });

How it works: If 2000ms pass without the browser becoming idle, the callback runs anyway during the next available opportunity—even if it means slightly delaying other work. The browser treats it as higher priority.

Checking If You're in Timeout Mode

Inside your callback, you can check deadline.didTimeout:

requestIdleCallback((deadline) => {
  if (deadline.didTimeout) {
    // Running due to timeout, do essential work only
    saveImportantData();
  } else {
    // Genuinely idle, can do more
    while (deadline.timeRemaining() > 0) {
      processQueueItem();
    }
  }
}, { timeout: 3000 });

Think of it like: Setting a timer for your friend to call you back. If they're free, great! If not, the timer guarantees they'll call within 3 seconds regardless.

Key Takeaway: Always use the timeout option for tasks that must eventually execute, balancing deferred performance optimization with guaranteed completion.