No, no, it’s 2020 and there’s no one who doesn’t know JSrAF???

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

! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/df21d1327c7448b6b9e5a57fd1f20095~tplv-k3u1fbpfcp-zoom-1.image)

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.

** “return value” ** A long integer, the request ID, that is the 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) {// timestamp callback function passed the 'DOMHighResTimeStamp' parameter, 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(' + Elapsed, 200) + 'px '; If (elapsed < 2000) {/ / stop in two seconds animation 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

“Top 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; Const timeCount = 3000; Const intervalTime = 10; // Set the interval to 10ms let runCount = timeCount/intervalTime; // Let moveValue = distance/runCount; Function handler() {let left = parseInt(divele.style.left); If (left >= distance) {// If (left >= distance) { } 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; Const timeCount = 3000; Function handler(time) {function handler(time) {// Time is the unit of milliseconds returned by rAF. If the value of time is greater than the value of timeCount, it will stop.  if(time > timeCount) { time = timeCount; } // Time is from 1 to 3000. Divele.style. left = time * distance/timeCount; window.requestAnimationFrame( handler ); / / call, rendering completed will stop} 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. ** “causes 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. “Execute when the page TAB or browser is not visible in the background, 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 perform perfectly:” **

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

! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c186eeb339b240dd96053c2ccaf2a49e~tplv-k3u1fbpfcp-zoom-1.image)

Our display is typically ** “16.7ms display frequency (60FPS)”, the first line of the figure represents the “16.7ms display frequency” displayed on most monitors, and the second line of the figure 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.

  • ** it ensures that every call to our animation function corresponds to a screen redraw, thus avoiding frame loss caused by setTimeout defining the animation frequency by time inconsistent with the screen refresh rate.

  • ** “Save system resources, improve performance and visual effects” ** When the page is placed in the background or hidden, it will automatically stop, no function execution, when the page is activated, it will restart from the last stopped state, so the performance cost is much less 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']; / / prefix browser window. / / when requestAnimationFrame does not exist when the for loop, 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 of 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!