requestIdleCallback API Basics
You'll learn how to schedule low-priority tasks to run during browser idle periods using the requestIdleCallback() API.
What Is requestIdleCallback?
Think of the browser's main thread like a busy restaurant kitchen. High-priority orders (user interactions, rendering) must be cooked immediately, but prep work (analytics, tracking, background sync) can happen whenever the kitchen has a quiet moment. requestIdleCallback() is how you tell the browser "run this function when you have free time."
The API schedules a callback to execute during idle periods—moments when the browser has finished its critical work and has time before the next frame or user interaction.
Basic Syntax
requestIdleCallback(callbackFunction, options);
The callback receives an IdleDeadline object with useful information:
requestIdleCallback((deadline) => {
// Check how much idle time remains
console.log(`Time remaining: ${deadline.timeRemaining()}ms`);
// Check if we were forced to run (timeout reached)
console.log(`Did timeout? ${deadline.didTimeout}`);
// Do non-critical work
processAnalytics();
});
Optional Timeout
You can specify a maximum wait time:
requestIdleCallback(doBackgroundWork, { timeout: 2000 });
// Will run within 2 seconds even if not idle
Working Within the Time Budget
Check remaining time to avoid blocking:
function processQueue(deadline) {
while (queue.length > 0 && deadline.timeRemaining() > 0) {
let item = queue.shift();
processItem(item);
}
if (queue.length > 0) {
requestIdleCallback(processQueue); // Continue later
}
}
Key Takeaway: requestIdleCallback() lets you schedule non-critical work to run during browser idle periods, checking deadline.timeRemaining() to avoid blocking the main thread and ensuring smooth user experiences.