Won’t, won’t, now all 2020 won’t return person somebody doesn’t know JS rAF??

rAF

Introduction to the

RAF is short for requestAnimationFrame;

We first understand requestAnimationFrame from literal meaning, “the request – request”, “Animation, Animation”, “Frame – Frame rate; the framework”, rAF is JS Animation framework??????? “Obviously not. But rAF does have something to do with animation

RequestAnimationFrame = requestAnimationFrame = requestAnimationFrame

Tell the browser window. RequestAnimationFrame () – you want to perform an animation, and required the browser until the next redraw calls the specified callback function to update the animation. This method takes as an argument a callback function that is executed before the browser’s next redraw

Browser compatibility


RequestAnimationFrame is compatible with IE10 and above, but the most commonly used CSS3 animation property was created after IE10. Before IE9, the basic implementation of animation was setTimeout/setInterval

Function and Usage

RequestAnimationFrame, for short rAF, is a method of the browser’s global object Window.

RAF is used to instruct the browser to execute its provided callback function the next time the screen image is redrawn, as opposed to setTimeout executing the corresponding animation function after a fixed time.

This is also rAF’s biggest advantage — it can ensure that every call of our animation function corresponds to a screen redraw, so as to avoid frame loss caused by setTimeout defining animation frequency by time inconsistent with screen refresh frequency.

Detailed usage

The requestAnimationFrame syntax is as follows:


window.requestAnimationFrame(callback)

Copy the code

“Parameter; callback” updates the function called by the animation frame before the next redraw (that is, the callback function above). The callback function is passed the DOMHighResTimeStamp parameter, which has the same return value as performing.now () and represents the time when requestAnimationFrame() started executing the callback function.

The “return value” is a long integer, the request ID, and is a unique identifier in the callback list. It’s a non-zero value, that’s all. You can send this value to the window. The cancelAnimationFrame () to cancel the callback function.

DOMHighResTimeStamp is a double that stores milliseconds of time. This type can be used to describe discrete points in time or periods of time (the difference between two discrete points in time).

The performance.now() method returns a DOMHighResTimeStamp with millisecond accuracy.


Its common practical use is similar to setTimeout, except that you don’t need to set the interval. As follows:


const element = document.getElementById('some-element-you-want-to-animate'); 
let start;

function step(timestamp) {
The timestamp callback function passes in the 'DOMHighResTimeStamp' parameter, which stores the value of the time in milliseconds if (start === undefined)  start = timestamp;  const elapsed = timestamp - start;  // Use 'math.min ()' here to make sure the element stops at exactly 200px. element.style.transform = 'translateX('Min (0.1 * Elapsed, 200) +'px)';   ifElapsed < 2000) {// Stop the animation after two seconds window.requestAnimationFrame(step);  } }  window.requestAnimationFrame(step);  Copy the code

This code works by moving the element 1px to the left and stopping at 200px for each update of the screen image.

Example

On talent,E G M,E G M E G M E G M

Let’s take an animation that moves 1500px in 3000 milliseconds

The implementation of setTimeout

The following code uses setTimeout to animate an element by changing its position every 10 milliseconds. Of course, you can fine-tune the animation by changing this interval, but you can never determine the optimal solution because it always intersects with the refresh rate.


<div id="div" style="width:100px; height:100px; background-color:#000; position: absolute; left:0; top:0;">
    
</div>

<script type="text/javascript"> let divEle = document.getElementById("div");  const distance = 1500; // The distance to moveconst timeCount = 3000; // Time required to use const intervalTime = 10; // Set the interval to 10msletrunCount = timeCount / intervalTime; // Divide to get the number of runsletmoveValue = distance / runCount; // The distance moved per run function handler() {  let left = parseInt(divEle.style.left);  if(left >= distance) { // Stop when the distance to the left exceeds the distance you need to move return;  }  divEle.style.left = left + moveValue;  window.setTimeout(handler, intervalTime); }  window.setTimeout(handler, intervalTime); </script>  Copy the code

RequestAnimationFrame implementation

Switching from setTimeout to requestAnimationFrame is easy because they both schedule a callback. For continuous animation, requestAnimationFrame is called again after the animation function is called.

Request will take all the DOM manipulation in each frame together, in a redrawn or circumfluence is complete (it’s like a virtual DOM not ~), the time interval and redrawn or return to follow the browser’s refresh rate, so as not to appear the problem of excessive rendering, demand to ensure the smooth and perfect rendering of the browser.


<div id="div" style="width:100px; height:100px; background-color:#000; position: absolute; left:0; top:0;">
    
</div>

<script type="text/javascript">  let divEle = document.getElementById("div");  const distance = 1500; // The distance to moveconst timeCount = 3000; // Time required to use function handler( time ) { // Time is the millisecond time unit returned by rAF. When time is greater than the value of timeCount, it stops// Time is theoretically from 1 to 3000 as defined by timeCount, if(time > timeCount) {  time = timeCount;  } // Time is from 1 to 3000Time * distance/timeCount = distance 1500 divEle.style.left = time * distance / timeCount; window.requestAnimationFrame( handler ); // loop to stop rendering}   window.requestAnimationFrame( handler ); </script>   Copy the code

The advantages of requestAnimationFrame

Why not use setTimeout?

SetTimeout completes the GIF by setting a time interval to continuously update the screen image. It has the advantage of high controllability and can realize the animation effect of coding.

SetTimeout faults:

  1. Cause useless function running overhead:

This means overdrawing, and because the frequency of updating images is out of step with the screen’s refresh and redrawing, frames can be lost and animations can look stuttering on low-performance displays.

  1. When the page label or browser is not visible in the background, it is still executed, resulting in a waste of resources

  2. The API itself is not millisecond accurate:

If you use setTimeout or setInterval then you need to specify a time and assume that given (1000/60) you can theoretically animate at 60 frames. Therefore, the elextricity of a browser can impose a timeout interval of 5-10 milliseconds. This means that even if you give a number less than 10, you may have to wait 10 milliseconds.

  1. Browsers don’t execute perfectly:

When the animation is drawn with setTimeout of 10ms, you will see a timing mismatch, as shown below.


Our display is typically “16.7ms (60FPS) display frequency.” the first line in the figure above represents the “16.7ms display frequency” displayed on most monitors, and the second line in the figure above represents “a typical setTimeout of 10ms.” The third draw of each draw cannot be drawn (indicated by the red arrow) because another draw request occurred before the display refresh interval. This overdraft can cause the animation to stutter “because every third frame is lost”. Reduced timer resolution can also have a negative impact on battery life and reduce the performance of other applications.

If you use requestAnimationFrame, you can solve the setTimeout frame loss problem because it lets the application notify (and only if) the browser that needs to update the page display, and the rendering time is handled by the system. As a result, the application paints exactly the same spacing as the browser and uses only the right amount of resources.

The benefits of requestAnimationFrame

RequestAnimationFrame is used to instruct the browser to execute its provided callback function the next time the screen image is redrawn, as opposed to setTimeout executing the corresponding animation function after a fixed time.

  • “Synchronize the redrawing and backflow of the browser picture with the refresh frequency of the display”. It can ensure that every call of our animation function corresponds to a screen redrawing, so as to avoid the loss of frames caused by setTimeout defining animation frequency by time inconsistent with the screen refresh frequency.

  • “Save system resources, improve performance and visual effect” will stop automatically when the page is placed in the background or hidden, and the function is not executed. When the page is activated, it will restart the execution from the last stopped state, so the performance cost is much smaller than setTimeout.

compatibility

At this point in time, almost all current versions of browsers support the requestAnimationFrame function. However, compatibility prefixes are required on some browsers. Here is a more comprehensive way to make requestAnimation compatible with all browsers:


(function() {
    var lastTime = 0;
    var vendors = ['webkit'.'moz']; // The browser prefix/ / when the window requestAnimationFrame doesn't existforLoop, add prefix for(var x = 0; x < vendors.length && ! window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];  window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] | | window[vendors[x] + 'CancelRequestAnimationFrame'];  }  // If the prefix still does not exist, use setTimeout instead if(! window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) {  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);  };  } } ()); Copy the code

We can then use the requestAnimationFrame method to animate with the setTimeout feeling.

A link to the

  • Zhang Xinxu – requestAnimationFrame

  • MDN – requestAnimationFrame

  • Microsoft – requestAnimationFrame

  • Personal website: zhaohongcheng.com

  • GitHub:github.com/Tzlibai

At the end

If you have any questions, please leave a comment below and we will reply as soon as possible

Thank you for taking the time to read this article. I hope it helps!

I’ve been on the top of mountains and I’ve been down on valleys, and I’ve learned a lot from both.