Why should I use requestAnimationFrame rather than setTimeout or setInterval?
This self-answered question is a documentation example.
Why should I use requestAnimationFrame rather than setTimeout or setInterval?
This self-answered question is a documentation example.
High quality animation.
The question is most simply answered with.
ShearrequestAnimationFrame
produces higher quality animation completely eliminating flicker and shear that can happen when usingsetTimeout
orsetInterval
, and reduce or completely remove frame skips.is when a new canvas buffer is presented to the display buffer midway through the display scan resulting in a shear line caused by the mismatched animation positions.
Flickeris caused when the canvas buffer is presented to the display buffer before the canvas has been fully rendered.
Frame skipis caused when the time between rendering frames is not in precise sync with the display hardware. Every so many frames a frame will be skipped producing inconsistent animation. (There are method to reduce this but personally I think these methods produce worse overall results) As most devices use 60 frames per second (or multiple of) resulting in a new frame every 16.666...ms and the timers
setTimeout
andsetInterval
use integers values they can never perfectly match the framerate (rounding up to 17ms if you haveinterval = 1000/60
)A demo is worth a thousand words.
Update The answer to the question requestAnimationFrame loop not correct fps shows how setTimeout's frame time is inconsistent and compares it to requestAnimationFrame.
The demo shows a simple animation (stripes moving across the screen) clicking the mouse button will switch between the rendering update methods used.
There are several update methods used. It will depend on the hardware setup you are running as to what the exact appearance of the animation artifacts will be. You will be looking for little twitches in the movement of the stripes