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);
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.