What is requestAnimationFrame?
The requestAnimationFrame is a method offered by the browser’s rendering the engine that helps optimize animations and visual updates and It schedules a function to be executed just before the browser’s next repaint typically in the sync with the screen’s refresh rate. This method is specifically designed to the create smooth and efficient animations on the web.
Syntax:
requestAnimationFrame(callback);
Example: This demonstrates and invokes a function called “animate” that logs “Animating…” continuously using requestAnimationFrame for smooth animations.
function animate() {
console.log('Animating...');
requestAnimationFrame(animate);
}
animate();
Output:
Animating...
SetTimeout VS RequestAnimationFrame
The setTimeout and requestAnimationFrame are functions that can be used to the execute code after a delay. However, they serve different purposes and are optimized for the different scenarios especially when it comes to the animations and performance.