Timers have always been at the heart of javascript animation. The key to writing an animation loop is knowing how long the delay is appropriate. On the one hand, the loop intervals must be short enough for the different animations to be smooth and smooth. On the other hand, the loop interval should be long enough to ensure that the browser is capable of rendering the changes produced. Most computer monitors refresh at 60Hz, which equates to about 60 redraws per second. Most browsers limit redrawing to the frequency at which the display can be redrawn, because beyond that the user experience will not improve. Therefore, the optimal loop interval for the smoothest animation is 1000ms/60, which is approximately 16.6ms
setTimeout
: Indicates that an action will be executed after a specified timesetInterval
: Sets how often an action should be performed. It is circular and can be used if you want to repeat the action
The problem with setTimeout and setInterval is that they’re not exact. Their inherent mechanism dictates that the interval parameter really just specifies the time at which the animation code is added to the browser UI thread queue for execution. If other tasks have already been added to the queue, the animation code will wait for the previous task to complete
requestAnimationFrame
: You do not need to set the interval
RequestAnimationFrame uses the system time interval to maintain the best drawing efficiency, and does not cause excessive drawing and overhead because the interval is too short. There is also no lag in using animations due to long intervals, allowing for a unified refresh mechanism for various web animation effects, such as requestAnimationFrame stopping when the browser window is closed and hidden, and continuing animation when the window is displayed again. Thus save system resources, improve system performance, improve visual effect.
RequestAnimationFrame paradigm
var start = null;
var element = document.getElementById('test');
element.style.position = 'absolute';
function step(timestamp) {
if(! start) start = timestamp;var progress = timestamp - start;
element.style.left = Math.min(progress / 10.200) + 'px';
if (progress < 2000) {
window.requestAnimationFrame(step); }}window.requestAnimationFrame(step);
Copy the code