a blog for those who code

Sunday 1 November 2015

Why requestAnimationFrame is better than setTimeout and setInterval in HTML5

In this post we are going to discuss that why requestAnimationFrame is better than setTimeout and setInterval for doing animation in HTML5 canvas element. All three requestAnimationFrame, setTimeout and setInterval helps us to do animation in HTML5 using canvas element. At first we will study how setTimeout and setInterval works and then will discuss why requestAnimationFrame is better that both of them.


setInterval() - It is method of doing 60 frames/second canvas animation. It calls another function or evaluates an expression at specified intervals of time and then returns a unique id of the performed action. To stop the animation you need to call clearInterval(id), where id is the unique id.

Syntax : setInterval(function, ms);

The disadvantages of using setInterval() is that it will create problem in debugging if you run several animations simultaneously. One more problem with setInterval() is that it will run the animation every n millisecond regardless of the time the function will take to execute. That means if the function takes too much time to execute, setInterval() might queue too many function execution.

setTimeout() - It works like setInterval(), but unlike setInterval() setTimeout() calls a function once and after a given amount of time.

Syntax : setTimeout(function, ms);

The disadvantage of using setTimeout() is that it does not wait during the timeout period and let the rest of the JavaScript code to run. This will give unreliable result in most of the cases where function will take little more time to execute.

requestAnimationFrame() - It tells the browser that you wish to perform the animation and it also requests to update an animation before the next repaint. requestAnimationFrame runs a callback after the browser paints the screen unlike setTimeout which runs after specified time delay. Animations can be performed by at first clearing the context, then drawing the shape, then moving the shape and then start all over again. cancelAnimationFrame(id) is used to stop the animation.

Syntax : requestAnimationFrame(function);

Advantage of requestAnimationFrame

1. The scheduling is much more accurate than setInterval() and setTimeout().
2. The requestAnimationFrame uses High Resolution Timer which helps it to do time based animation. Time based animation smoothens the animation even if the frame rates are not constant.
3. Multiple animations are possible using requestAnimationFrame.
4. CPU optimization is done using requestAnimationFrame by not drawing when tab or window is not visible.

Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.

1 comment: