requestIdleCallback for low-priority work
| 1 min read
Some work just isn’t urgent. Logging analytics, prefetching the next page, warming up a cache, hydrating something off-screen. You don’t want it competing with user input or rendering.
requestIdleCallback schedules a callback for when the browser thinks it has spare time.
requestIdleCallback((deadline) => {
// do work while the browser is idle
console.log("Idle for", deadline.timeRemaining(), "ms");
});
The deadline object tells you how long you’ve got. Bail out early if you’re running long, and reschedule the rest:
function processQueue(queue) {
requestIdleCallback((deadline) => {
while (deadline.timeRemaining() > 0 && queue.length) {
const task = queue.shift();
task();
}
if (queue.length) processQueue(queue); // pick up next idle slot
});
}
For absolute “must run within X ms” guarantees, pass a timeout:
requestIdleCallback(doWork, { timeout: 1000 });
After 1000ms the callback fires whether the browser’s idle or not. The deadline.didTimeout flag will be true so you can skip the heavier work and just do the bare minimum.
Two things worth knowing —
- Safari only added support relatively recently. For older targets, fall back to
setTimeout(fn, 0). - Don’t use this for anything user-facing or animation-related,
requestAnimationFrameis the right tool there.