Introduced
Timers have always been the core technology of javascript animation. The key to writing an animation loop is to know how long the delay is appropriate. On the one hand, the loop interval must be short enough so that different animation effects can appear smooth and smooth; on the other hand, the loop interval must be long enough so that the browser can render changes.
The refresh frequency of most computer monitors is 60Hz, which is roughly equivalent to repainting 60 times per second. Most browsers will limit the redraw operation to not exceed the monitor's redraw frequency, because even if it exceeds that frequency, the user experience will not improve. Therefore, the optimal loop interval for the smoothest animation is 1000ms/60, which is approximately equal to 16.6ms
And the problem with setTimeout and setInterval is that neither they are accurate. Their intrinsic running mechanism determines that the time interval parameters actually just specify how long to add animation code to the browser UI thread queue to wait for execution. If other tasks have been added to the queue, the animation code must wait until the previous tasks are completed before executing them.
RequestAnimationFrame uses system time intervals to maintain the best drawing efficiency, and will not overdraw due to the short interval time, which will increase overhead; nor will the use of animations be stuck and not smooth because the interval time is too long, so that various web animation effects can have a unified refresh mechanism, thereby saving system resources, improving system performance, and improving visual effects
Features
【1】The requestAnimationFrame will concentrate all DOM operations in each frame, complete in a single repaint or reflow, and the time interval of repaint or reflow is closely followed by the refresh frequency of the browser
【2】In hidden or invisible elements, the requestAnimationFrame will not be repainted or reflowed, which of course means less CPU, GPU and memory usage
【3】requestAnimationFrame is an API provided by the browser specifically for animation. When run, the browser will automatically optimize the call of the method. If the page is not activated, the animation will automatically pause, effectively saving CPU overhead
use
The usage of requestAnimationFrame is very similar to settimeout, except that there is no need to set the time interval. The requestAnimationFrame uses a callback function as a parameter, which is called before the browser repaints. It returns an integer representing the timer's number, which can be passed to cancelAnimationFrame to cancel the execution of this function
requestID = requestAnimationFrame(callback); //Console outputs 1 and 0var timer = requestAnimationFrame(function(){console.log(0);}); console.log(timer); //1 cancelAnimationFrame method is used to cancel the timer//Console outputs nothing var timer = requestAnimationFrame(function(){console.log(0);}); cancelAnimationFrame(timer);You can also use the return value to cancel it directly
var timer = requestAnimationFrame(function(){console.log(0);}); cancelAnimationFrame(1);compatible
IE9-Browser does not support this method, you can use setTimeout for compatibility
if(!window.requestAnimationFrame){var lastTime = 0;window.requestAnimationFrame = function(callback){var currTime = new Date().getTime();var timeToCall = Math.max(0,16.7-(currTime - lastTime));var id = window.setTimeout(function(){callback(currTime + timeToCall);},timeToCall);lastTime = currTime + timeToCall; return id;}} if (!window.cancelAnimationFrame) {window.cancelAnimationFrame = function(id) {clearTimeout(id);};}application
Now use the three methods of setInterval, setTimeout and requestAnimationFrame to create a simple system effect.
【1】setInterval
<div id="myDiv" style="background-color: lightblue;width: 0;height: 20px;line-height: 20px;">0%</div><button id="btn">run</button><script>var timer;btn.onclick = function(){clearInterval(timer);myDiv.style.width = '0';timer = setInterval(function(){if(parseInt(myDiv.style.width) < 500){myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';myDiv.innerHTML = parseInt(myDiv.style.width)/5 + '%'; }else{clearInterval(timer);} },16);}</script>【2】setTimeout
<div id="myDiv" style="background-color: lightblue;width: 0;height: 20px;line-height: 20px;">0%</div><button id="btn">run</button><script>var timer;btn.onclick = function(){clearTimeout(timer);myDiv.style.width = '0';timer = setTimeout(function fn(){if(parseInt(myDiv.style.width) < 500){myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';myDiv.innerHTML = parseInt(myDiv.style.width)/5 + '%';timer = setTimeout(fn,16);}else{clearTimeout(timer);} },16);}</script>【3】requestAnimationFrame
<div id="myDiv" style="background-color: lightblue;width: 0;height: 20px;line-height: 20px;">0%</div><button id="btn">run</button><script>var timer;btn.onclick = function(){myDiv.style.width = '0';cancelAnimationFrame(timer);timer = requestAnimationFrame(function fn(){if(parseInt(myDiv.style.width) < 500){myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';myDiv.innerHTML = parseInt(myDiv.style.width)/5 + '%';timer = requestAnimationFrame(fn);}else{cancelAnimationFrame(timer);} });}</script>Okay, the code is here to introduce the third timer application in the BOM series (clock, countdown, stopwatch and alarm clock)
The above is the second timer requestAnimationFrame of the BOM series introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!