How to Use requestIdleCallback in JavaScript: Syntax and Examples
Use
requestIdleCallback in JavaScript to schedule a function to run when the browser is idle, helping improve performance by running non-urgent tasks later. Pass a callback function to requestIdleCallback, which receives a deadline object to check remaining idle time.Syntax
The requestIdleCallback function takes a callback that runs when the browser is idle. The callback receives a deadline object to check how much idle time is left.
- callback: A function called during idle time with a
deadlineparameter. - options (optional): An object with a
timeoutproperty to force callback after a max wait time.
javascript
requestIdleCallback(callback, { timeout: 1000 });
// callback example:
function callback(deadline) {
while (deadline.timeRemaining() > 0 && tasks.length > 0) {
doTask(tasks.shift());
}
}Example
This example schedules a task to run when the browser is idle. It logs messages showing when the idle callback runs and how much time is left.
javascript
function idleTask(deadline) { console.log('Idle callback started'); while (deadline.timeRemaining() > 0) { console.log('Time remaining:', deadline.timeRemaining()); break; // Just one iteration for demo } console.log('Idle callback finished'); } requestIdleCallback(idleTask);
Output
Idle callback started
Time remaining: 50
Idle callback finished
Common Pitfalls
Common mistakes include:
- Not checking
deadline.timeRemaining()inside the callback, which can cause long tasks to block the main thread. - Assuming
requestIdleCallbackruns immediately; it only runs during idle periods. - Not providing a
timeoutoption, which can delay important tasks indefinitely if the browser never becomes idle.
javascript
/* Wrong: Long task without checking timeRemaining */ requestIdleCallback(() => { for (let i = 0; i < 1e9; i++) { /* heavy loop */ } console.log('Heavy task done'); }); /* Right: Check timeRemaining to avoid blocking */ requestIdleCallback((deadline) => { while (deadline.timeRemaining() > 0 && tasks.length > 0) { doTask(tasks.shift()); } });
Quick Reference
| Feature | Description |
|---|---|
| requestIdleCallback(callback, options) | Schedules callback during browser idle time |
| callback(deadline) | Function called with deadline object |
| deadline.timeRemaining() | Returns ms left in idle period |
| options.timeout | Max wait time before callback runs |
Key Takeaways
Use requestIdleCallback to run low priority tasks during browser idle time.
Always check deadline.timeRemaining() inside the callback to avoid blocking.
Provide a timeout option to ensure important tasks run eventually.
requestIdleCallback improves performance by deferring non-urgent work.
It is not supported in all browsers; consider fallbacks if needed.