Testing - Oh My JS: The Best JavaScript Articles (2014)

Oh My JS: The Best JavaScript Articles (2014)

Testing

Leaner, Meaner, Faster Animations with requestAnimationFrame

Original Article

http://www.html5rocks.com/en/tutorials/speed/animations

Paul Lewis, html5rocks.com

It’s a fair bet you’ve done some animation work in your time as a developer, whether that’s smaller UI effects or large iteractive canvas pieces. Chances are you’ve also come across requestAnimationFrame, or rAF (we say it raff around these parts), and hopefully you’ve had a chance to use it in your projects. In case you don’t know, requestAnimationFrame is the browser’s native way of handling your animations. Because rAF is specifically designed to deal with animation and rendering, the browser can schedule it at the most appropriate time and, if we play our cards right, it will help us get a buttery smooth 60 frames per second.

What we want to do in this article is outline some additional ways to ensure you’re getting the maximum benefit from your animation code. Even if you’re using requestAnimationFrame there are other ways you can end up with bottlenecks in your animations. At 60 frames per second each frame that you draw has 16.67ms to get everything done. That’s not a lot, so every optimisation counts!

TL;DR Decouple your events from animations; avoid animations that result in reflow-repaint loops; update your rAF calls to expect a high resolution timestamp as the first parameter; only call rAF when you have visual updates to do.

Debouncing Scroll Events

Debouncing is the process of decoupling your animation from any inputs that affect it. Take, for example, an effect that is triggered when you scroll the page. The effect might check if some DOM elements are visible to the user and then, if they are, apply some CSS classes to those elements.

Or maybe you’re coding a parallax scrolling effect where, as you scroll, background images change their position relative to page’s scroll position. I’ll go with the former of the two common uses, and the general gist of our code might be:

1 function onScroll() {

2 update();

3 }

4

5 function update() {

6

7 // assume domElements has been declared

8 // by this point :)

9 for(var i = 0; i < domElements.length; i++) {

10

11 // read offset of DOM elements

12 // to determine visibility - a reflow

13

14 // then apply some CSS classes

15 // to the visible items - a repaint

16

17 }

18 }

19

20 window.addEventListener('scroll', onScroll, false);

The main issue here is that we are triggering a reflow and repaint whenever we get a scroll event: we ask the browser to recalculate the real positions of DOM elements, an expensive reflow operation, and then we apply some CSS classes, which causes the browser to repaint. We end up ping-ponging between reflowing and repainting, and this is going to undermine your app’s performance. We’re picking on scroll events here, but the same applies to resize events. In fact, any event that you’re going to make use of in this way can cause performance issues. Read Tony Gentilcore’s Fastersite blog post for a breakdown of properties that cause a reflow in WebKit.

What we now need to do is decouple the scroll event from the update function, and this is exactly where requestAnimationFrame steps in to help. We need to change things around so that we are listening to our scroll events, but we will only store the most recent value:

1 var latestKnownScrollY = 0;

2

3 function onScroll() {

4 latestKnownScrollY = window.scrollY;

5 }

Now we’re in a better place: onScroll runs whenever the browser chooses to execute it, but all we’re doing is storing the window’s scroll position. This code could run once, twenty or a hundred times before we try to use the value in our animation and it wouldn’t matter. The point is that we’re keeping a track on the value but it’s not using it to trigger potentially unnecessary draw calls. If your draw call is expensive then you’ll really benefit from avoiding those extra calls.

The other part of this change is to use requestAnimationFrame to handle the visual updates at the most convenient time for the browser:

1 function update() {

2 requestAnimationFrame(update);

3

4 var currentScrollY = latestKnownScrollY;

5

6 // read offset of DOM elements

7 // and compare to the currentScrollY value

8 // then apply some CSS classes

9 // to the visible items

10 }

11

12 // kick off

13 requestAnimationFrame(update);

Now we’re just pulling the latest value from lastKnownScrollY when we need it and discarding everything else. If you need to capture all the event values since the last draw you could use an array and push all the values captured in onScroll onto it. When the time comes to do the drawing you could average the values or do whatever’s most appropriate. In this case we’re keeping it simple and only tracking the last value we captured.

What else can we do? Well for one thing we are constantly running requestAnimationFrame and that’s not necessary if we haven’t just scrolled since nothing will have changed. To fix that we have the onScroll initiate the requestAnimationFrame:

1 var latestKnownScrollY = 0,

2 ticking = false;

3

4 function onScroll() {

5 latestKnownScrollY = window.scrollY;

6 requestTick();

7 }

8

9 function requestTick() {

10 if(!ticking) {

11 requestAnimationFrame(update);

12 }

13 ticking = true;

14 }

Now whenever we scroll we will try and call requestAnimationFrame, but if one is already requested we don’t initiate another. This is an important optimization, since the browser will stack all the repeated rAF requests and we would be back to a situation with more calls to update than we need.

Thanks to this setup we no longer need to call requestAnimationFrame at the top of update because we know it will only be requested when one or more scroll events has taken place. We also no longer need the kick off call at the bottom, either, so let’s update accordingly:

1 function update() {

2 // reset the tick so we can

3 // capture the next onScroll

4 ticking = false;

5

6 var currentScrollY = latestKnownScrollY;

7

8 // read offset of DOM elements

9 // and compare to the currentScrollY value

10 // then apply some CSS classes

11 // to the visible items

12 }

13

14 // kick off - no longer needed! Woo.

15 // update();

Hopefully you can see the benefits of debouncing the animations in your app from any scroll or resize events that influence it. If you’re still in any doubt, John Resig wrote a great article about how Twitter was affected by scroll events a while ago. Had rAF been around back then, the above technique would have probably been his recommendation.

Debouncing Mouse Events

We’ve gone through one common use-case for using rAF to decouple animations from scroll and resize events, now let’s talk about another one: using it to deal with interactions. In this instance we’re going to have something stick to the current mouse position, but only when the mouse button is pressed. When it’s released we’ll stop the animation.

Let’s jump straight into the code, then we’ll pick it apart:

1 var mouseIsDown = false,

2 lastMousePosition = { x: 0, y: 0 };

3

4 function onMouseDown() {

5 mouseIsDown = true;

6 requestAnimationFrame(update);

7 }

8

9 function onMouseUp() {

10 mouseIsDown = false;

11 }

12

13 function onMouseMove(evt) {

14 lastMousePosition.x = evt.clientX;

15 lastMousePosition.y = evt.clientY;

16 }

17

18 function update() {

19 if(mouseIsDown) {

20 requestAnimationFrame(update);

21 }

22

23 // now draw object at lastMousePosition

24 }

25

26 document.addEventListener('mousedown', onMouseDown, false);

27 document.addEventListener('mouseup', onMouseUp, false);

28 document.addEventListener('mousemove', onMouseMove, false);

In this instance we are setting a boolean (mouseIsDown) depending on whether or not the mouse button is currently pressed. We can also piggy back on the mousedown event to initiate the first requestAnimationFrame call, which is handy. As we move the mouse we do a similar trick to the previous example where we simply store the last known position of the mouse, which we later use in the update function. The last thing to notice is that update requests the next animation frame until we’ve called onMouseUp and mouseIsDown is set back to false.

Again our tactic here is to let the mouse events all proceed as often as the browser deems necessary, and we have the draw calls happen independently of those events. Not dissimilar to what we do with scroll events.

If things are a little more complex and you’re animating something that carries on moving after onMouseUp has been called, you’ll need to manage the calls to requestAnimationFrame differently. A suitable solution is to track the position of the animating object and when the change on two subsequent frames drops below a certain threshold you stop calling requestAnimationFrame. The changes to our code would look a little like this:

1 var mouseIsDown = false,

2 lastMousePosition = { x: 0, y: 0 },

3 rAFIndex = 0;

4

5 function onMouseDown() {

6 mouseIsDown = true;

7

8 // cancel the existing rAF

9 cancelAnimationFrame(rAFIndex);

10

11 rAFIndex = requestAnimationFrame(update);

12 }

13

14 // other event handlers as above

15

16 function update() {

17

18 var objectHasMovedEnough = calculateObjectMovement();

19

20 if(objectHasMovedEnough) {

21 rAFIndex = requestAnimationFrame(update);

22 }

23

24 // now draw object at lastMousePosition

25 }

26

27 function calculateObjectMovement() {

28

29 var hasMovedFarEnough = true;

30

31 // here we would perhaps use velocities

32 // and so on to capture the object

33 // movement and set hasMovedFarEnough

34 return hasMovedFarEnough;

35 }

The main change in the above comes from the fact that if you release the mouse the rAF calls would continue until the object has come to a rest but you may start clicking and dragging again meaning you would get a second rAF call scheduled as well as the original. Not good. To combat this we make sure to cancel any scheduled requestAnimationFrame call (in onMouseDown) before we set about issuing a new one.

requestAnimationFrame and High Resolution Timestamps

While we’re spending some time talking about requestAnimationFrame it’s worth noting a recent change to how callbacks are handled in Canary. Going forward the parameter passed to your callback function will be a high resolution timestamp, accurate to a fraction of a millisecond. Two things about this:

1. It’s awesome for your animations if they’re time-based because now they can be really accurate

2. You’ll need to update any code you have in place today that expects an object or element to be the first parameter

Get the full rundown of this at: requestAnimationFrame API: now with sub-millisecond precision

An Example

OK, let’s finish this article off with an example, just so you can see it all in action. It’s slightly contrived, and we’ll also throw in a bonus performance killer that we can fix as we go. Way too much fun!

We have a document with 800 DOM elements that we’re going to move when you scroll the mouse. Because we’re well-versed in modern web development we’re going to use CSS transitions and requestAnimationFrame from the off. As we scroll down the page we’ll determine which of our 800 DOM elements are now above the middle of the visible area of the screen and we’ll move them over to the left hand side by adding a left class.

It’s worth bearing in mind that we’ve chosen such a large number of elements because it will allow us to really see any performance issues more easily. And there are some.

Here’s what our JavaScript looks like:

1 var movers = document.querySelectorAll('.mover');

2

3 /**

4 * Set everthing up and position all the DOM elements

5 * - normally done with the CSS but, hey, there's heaps

6 * of them so we're doing it here!

7 */

8 (function init() {

9

10 for(var m = 0; m < movers.length; m++) {

11 movers[m].style.top = (m * 10) + 'px';

12 }

13

14 })();

15

16 /**

17 * Our animation loop - called by rAF

18 */

19 function update() {

20

21 // grab the latest scroll position

22 var scrollY = window.scrollY,

23 mover = null,

24 moverTop = [],

25 halfWindowHeight = window.innerHeight * 0.5,

26 offset = 0;

27

28 // now loop through each mover div

29 // and change its class as we go

30 for(var m = 0; m < movers.length; m++) {

31

32 mover = movers[m];

33 moverTop[m] = mover.offsetTop;

34

35 if(scrollY > moverTop[m] - halfWindowHeight) {

36 mover.className = 'mover left';

37 } else {

38 mover.className = 'mover';

39 }

40

41 }

42

43 // keep going

44 requestAnimationFrame(update);

45 }

46

47 // schedule up the start

48 window.addEventListener('load', update, false);

Our demo page before performance and rAF optimizations

If you check out the pre-optimized page you’ll see it really struggle to keep up as you scroll, and there are a number of reasons why. Firstly we are brute force calling the requestAnimationFrame, whereas what we really should do is only calculate any changes when we get a scroll event. Secondly we are calling offsetTop which causes a reflow, but then we immediately apply the className change and that’s going to cause a repaint. And then thirdly, for our bonus performance killer, we are using className rather than classList.

The reason using className is less performant than classList is that className will always affect the DOM element, even if the value of className hasn’t changed. By just setting the value we trigger a repaint, which can be very expensive. Using classList, however, allows the browser to be much more intelligent about updates, and it will leave the element alone should the list already contain the class you’re adding (which is left in our case).

If you want more information on using classList and the new-and-extremely-useful frame breakdown mode in Chrome’s Dev Tools you should watch this video by Paul Irish:

So let’s take a look at what a better version of this would look like:

1 var movers = document.querySelectorAll('.mover'),

2 lastScrollY = 0,

3 ticking = false;

4

5 /**

6 * Set everthing up and position all the DOM elements

7 * - normally done with the CSS but, hey, there's heaps

8 * of them so we're doing it here!

9 */

10 (function init() {

11

12 for(var m = 0; m < movers.length; m++) {

13 movers[m].style.top = (m * 10) + 'px';

14 }

15

16 })();

17

18 /**

19 * Callback for our scroll event - just

20 * keeps track of the last scroll value

21 */

22 function onScroll() {

23 lastScrollY = window.scrollY;

24 requestTick();

25 }

26

27 /**

28 * Calls rAF if it's not already

29 * been done already

30 */

31 function requestTick() {

32 if(!ticking) {

33 requestAnimationFrame(update);

34 ticking = true;

35 }

36 }

37

38 /**

39 * Our animation callback

40 */

41 function update() {

42 var mover = null,

43 moverTop = [],

44 halfWindowHeight = window.innerHeight * 0.5,

45 offset = 0;

46

47 // first loop is going to do all

48 // the reflows (since we use offsetTop)

49 for(var m = 0; m < movers.length; m++) {

50

51 mover = movers[m];

52 moverTop[m] = mover.offsetTop;

53 }

54

55 // second loop is going to go through

56 // the movers and add the left class

57 // to the elements' classlist

58 for(var m = 0; m < movers.length; m++) {

59

60 mover = movers[m];

61

62 if(lastScrollY > moverTop[m] - halfWindowHeight) {

63 mover.classList.add('left');

64 } else {

65 mover.classList.remove('left');

66 }

67

68 }

69

70 // allow further rAFs to be called

71 ticking = false;

72 }

73

74 // only listen for scroll events

75 window.addEventListener('scroll', onScroll, false);

Our demo page after performance and rAF optimizations

If you look at our new optimized version of the demo you will see much smoother animations as you scroll up and down the page. We’ve stopped calling requestAnimationFrame indiscriminantly, we now only do it when we scroll (and we ensure there is only one call scheduled). We’ve also moved the offsetTop property lookups into one loop and put the class changes into a second loop which means that we’re avoiding the reflow-repaint problem. We’ve decoupled our events from the draw call so they can happen as often as they like and we won’t be doing unnecessary drawing. Finally we’ve switched out className for classList, which is a massive performance saver.

Of course there are other things we can do to take this further, in particular not iterating through all 800 DOM elements on each pass, but even just the changes we’ve made have given us great performance improvements.

Conclusion

It’s important to not only use requestAnimationFrame for your animations, but also to use it in the right way. As you can hopefully see it’s quite easy to inadvertently cause bottlenecks, but by understanding how the browser actually executes your code you can fix any problems quickly. Take some time with Chrome’s Dev Tools, especially the frame mode, and see where your animations can be improved.