The timer requestAnimationFrame added in html5 implements the progress bar function,
Before the emergence of requestAnimationFrame, we usually use setTimeout and setInterval. So why does html5 Add a new requestAnimationFrame?
Advantages and features:
1) requestAnimationFrame gathers all DOM operations in each frame and completes the re-painting or backflow at a time. The re-painting or backflow interval closely follows the refreshing frequency of the browser.
2) In hidden or invisible elements, requestAnimationFrame will not be repainted or reflux, which of course means less CPU, GPU, and memory usage.
3) requestAnimationFrame is an API provided by the browser for animation. At runtime, the browser automatically calls the optimization method. If the page is not activated, the animation will be automatically paused, effectively saves CPU overhead
In a word, the frame rate is automatically adjusted based on different browsers because the performance is high and the screen is not flushed. It doesn't matter if you don't understand it or you don't understand it. This is related to the browser Rendering Principle. Let's learn how to use it first!
How to Use requestAnimationFrame?
The usage is similar to that of the timer setTimeout. The difference is that it does not need to set the time interval parameter.
Var timer = requestAnimationFrame (function () {console. log ('timer Code ');});
A parameter is a callback function. The return value is an integer used to indicate the number of the timer.
<! DOCTYPE html>
CancelAnimationFrame is used to disable the timer.
This method requires processing compatibility:
Simple compatibility:
window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); };})();
If the browser does not know AnimationFrame, it uses setTimeout compatibility.
Use three different timers (setTimeout, setInterval, requestAnimationFrame) to load a progress bar.
I. setInterval mode:
<! DOCTYPE html>
Ii. setTimeout
<script> window.onload = function(){ var oBtn = document.querySelector( "input" ), oBox = document.querySelector( "div" ), timer = null, curWidth = 0, getStyle = function( obj, name, value ){ if( obj.currentStyle ) { return obj.currentStyle[name]; }else { return getComputedStyle( obj, false )[name]; } }; oBtn.onclick = function(){ clearTimeout( timer ); oBox.style.width = '0'; timer = setTimeout( function go(){ curWidth = parseInt( getStyle( oBox, 'width' ) ); if ( curWidth < 1000 ) { oBox.style.width = oBox.offsetWidth + 10 + 'px'; oBox.innerHTML = parseInt( getStyle( oBox, 'width' ) ) / 10 + '%'; timer = setTimeout( go, 1000 / 60 ); }else { clearInterval( timer ); } }, 1000 / 60 ); } } </script>
Iii. requestAnimationFrame
<! DOCTYPE html>