What's the relationship between requestAnimationFrame and the event loop's rendering step?
Short answer
requestAnimationFrame schedules a callback to run right before the browser's next repaint, after microtasks have drained — making it the right tool for visual updates synced to the display's refresh rate, unlike setTimeout which has no such guarantee.
Advertisement
AModel answer
requestAnimationFrame schedules a callback to run right before the browser's next repaint, after microtasks have drained — making it the right tool for visual updates synced to the display's refresh rate, unlike setTimeout which has no such guarantee.
function animate() {
element.style.left = `${position++}px`;
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);Real-world example
Building a smooth custom animation that stays in sync with the browser's actual repaint cycle, avoiding jank.
Likely follow-ups
- Why is requestAnimationFrame generally preferred over setInterval for animations?
Related topics