requestAnimationFrame and requestIdleCallback in JavaScript
requestAnimationFrame
requestAnimationFrame is a browser method that allows executing a function before the next frame repaint. Used mainly for creating smooth animations and optimizing rendering.
requestAnimationFrame Syntax
const id = requestAnimationFrame(callback);
requestAnimationFrame Example
function animate(time) {
// update state or move element
box.style.transform = `translateX(${time / 10}px)`;
requestAnimationFrame(animate); // continue loop
}
requestAnimationFrame(animate);
Advantages:
- Synchronized with screen refresh rate (usually 60 FPS).
- Browser can optimize performance by skipping frames if tab isn't active.
- Better than
setInterval / setTimeoutfor animations.
requestIdleCallback
requestIdleCallback is a method that allows executing tasks when the browser is "idle" — during idle periods.
Suitable for non-time-critical tasks: background analytics, non-essential rendering, localStorage work, etc.
requestIdleCallback Syntax
const id = requestIdleCallback(callback, { timeout: 1000 });
requestIdleCallback Example
requestIdleCallback((deadline) => {
while (deadline.timeRemaining() > 0 && tasks.length > 0) {
doTask(tasks.shift());
}
});
deadline Argument
deadline.timeRemaining()— how many milliseconds remain before repaint.deadline.didTimeout— flag if timeout triggered.
Important:
requestIdleCallback is not supported in all browsers (e.g., Safari), so consider using a polyfill or fallback to setTimeout.
When to Use
requestAnimationFrame— for creating animations, progress bars, sliders, canvas.requestIdleCallback— for non-priority tasks: loading secondary scripts, analytics, backend synchronization.