I'm confused by requestAnimationFrame

Is there a way to control the timing of the callback? What can you do with requestAnimationFrame that you can’t do with the web animations API or css animations?

You can control the timing by using a timer inside your requestAnimationFrame function. It’s not the most ideal solution, but it gets very close.

Advantages over CSS Animations
With CSS animations, you are stuck animating CSS properties on elements. While that allows you to do a lot, it is also limiting. You have to deal with predefined keyframes. Not everything you want to do can be done in CSS. JavaScript provides you with a lot more flexibility at the expense of some gnarly looking code.

Advantages over the Web Animations API
The Web Animations API (WAAPI) meets you half-way between the flexibility of JavaScript and the ease/comfort of CSS Animations. You are still predefining your “keyframes” in JavaScript, but it is much easier to intercept and make changes to the animation compared to fiddling with CSS. (see example/tutorial)

The biggest drawback in my opinion is browser support. While there are polyfills out there for it, they aren’t the most performant of things.

Overall
If what you are animating is predefined and doesn’t require any randomness/physics/etc., both CSS Animations and WAAPI are great. If you are animating things on the canvas, doing something visually complex involving dynamic elements, or you just plain like JavaScript, requestAnimationFrame has got you covered.

What are you trying to animate? Maybe we can shed some tips on what approach might work better for your needs :stuck_out_tongue:

Cheers,
Kirupa

Thanks Kirupa. I’m trying to animate all sorts of things! :slight_smile:
I find requestAnimationFrame hard to work with compared to WAAPI and CSS (I managed to crash my browser!). Luckily I don’t think I really ever need it to achieve what I want.

1 Like