17
RequestAnimationFrame in JavaScript
Using the native requestAnimationFrame method we can make our browser repeat something very quickly forever. It calls itself to paint the next frame.
π Note: Your callback routine must itself call requestAnimationFrame() again if you want to animate another frame at the next repaint. requestAnimationFrame() is 1 shot.
requestAnimationFrame takes one argument, only callback.
Syntax:
window.requestAnimationFrame(callback);
callback: The function to call when it's time to update your animation for the next repaint.
Animations with requestAnimationFrame are non-blocking, which means if you make subsequent calls to requestAnimationFrame, the resulting animations will all occur at same time.
The goal is 60 frame per second(fps) to appear smooth animation.
So we do like this π
setInterval(() => {
// animation code
}, 1000/60);
But now we have requestAnimationFrame, which is more better and optimized:
- Animations will be so smooth as its optimized
- Animations in inactive tabs will stop, allowing the CPU to chill
Let's see how can we create the above snippet using requestAnimationFrame
function smoothAnimation() {
// animtion
requestAnimationFrame(smoothAnimation)
}
requestAnimationFrame(smoothAnimation)
requestAnimationFrame returns an ID you can use to cancel it.
let reqAnimationId;
function smoothAnimation() {
// animtion
reqAnimationId = requestAnimationFrame(smoothAnimation)
}
// to start
function start() {
reqAnimationId = requestAnimationFrame(smoothAnimation)
}
// to end
function end() {
cancelAnimationFrame(reqAnimationId)
}
console.log("reqAnimationId", reqAnimationId)
Checkout the codepen here for more details:
If you do any animation on browser and wanted it to be optimised, then would highly recommend to use requestAnimationFrame web API.
Thanks for reading the article β€οΈ
I hope you love the article.
π Twitter | π©π»βπ» suprabha.me | π Instagram |
17