Controlling the Animation

One way to pause a running animation is simply to inhibit the action as shown in the first example below, and based on the following code. As you can see, the window.requestAnimationFrame is still called, but setting the value of running to false merely prevents anything from getting done.

If you want to stop the animation entirely you can invoke the window.cancelAnimationFrame function, which takes a request ID for a parameter. That ID is actually returned by the window.requestAnimationFrame function. This ID wasn’t necessary when we didn’t want to do anything but start the animation, but is if you want to stop it directly. The ID is used internally by the browser in a way that supports multiple animation requests at the same time.

Next we can work on controlling the frame rate.

Here we embed the animation call and the window.requestAnimationFrame function in a timer so the refresh is only executed when the timing wrapper allows it. I’ve set it up so you can click to cycle from 20fps to 140fps in increments of 20fps. Your results may vary by browser and hardware but I didn’t notice that the animation was able to run at full speed until the setting was bumped up to 80fps, and occasional hiccups remained even then. I know that the refresh rate on my hardware is 60fps so I’m guessing that the effective time between updates is governed by the timer setting plus the time it takes for the next refresh to happen within the browser.

It appears that using this mechanism only makes sense when you want to manually slow the refresh rate down to well below the screen’s refresh rate. Also bear in mind that the browser may update less often than the hardware refresh rate if the system is busy, if individual animation cycles become too complex, or for other reasons.

This entry was posted in Tools and methods and tagged , , . Bookmark the permalink.

Leave a Reply