preface

Sunny, with great interest, opened before writing a simple animation plug-in, found that is written with timer, but as a pursuit of the front end, how can a problem have a solution? So, searching for information, finally see the dawn, let me check the requestAnimationFrame host object method, can also gracefully implement JS animation!

Traditional animation implementation

In our front-end tradition, in the old ie era, we had to use the setTimeout or setInterval functions to achieve animation. Let’s consider a question:

We take a number that starts at 0 and gets bigger, gets smaller as it gets to 100, and so on

So, how to write the traditional timer? Cut to the code

/ / CSS part < style >#a {
        font-size: 30px;
      }
    </style>
Copy the code
// HTML section <div id="a"></div>
Copy the code
Var e = document.getelementById ("a");
      var flag = true;
      var left = 0;

      function render() {
        if (flag == true) {
          if (left >= 100) {
            flag = false;
          }
          e.innerHTML = left++;
        } else {
          if (left <= 0) {
            flag = true; } e.innerHTML = left--; }}setInterval(function () {
        render();
      }, 1000/60);
Copy the code

The above writing method can be achieved in a cycle of large and small operation!

Does this approach work? Of course it works. Is it perfect? When you suddenly discover the new world, the timer is completely ended. For example, when you use Apple Retina screen, you find that there is no return. Do you think the 1080p screen is perfect? It’s perfect, but when you get Retina, it smells good!

window.requestAnimationFrame

Before we get to requestAnimationFrame, let’s take a look at a few concepts and explain why requestAnimationFrame smells good

What is the screen refresh rate

The reason we can see the movie, some animation effects, completely by our monitor continuously broadcast images, in a short time when play speed too fast, then formed the animation effects, while we display in the image, generally have a broadcast frequency standard, we call the screen refresh rate, the speed of the image on the screen update, This is the number of times a screen image appears per second, measured in Hertz (Hz). Under normal circumstances, when the refresh rate reaches 60Hz, basically our naked eye will not feel it is static, become a continuous animation!

Do you know why?

Why don’t you feel this change? That is because people’s eyes have visual retention effect, that is, the impression of the previous picture in the brain has not disappeared, followed by the next picture followed by the middle of the 16.7ms interval (1000/60≈16.7), so you will mistakenly think that the image on the screen is still. The screen is right. If the refresh rate is 1 refresh per second, the image on the screen will flicker severely, which can easily cause eye strain, soreness and dizziness. (Have nothing to do with the topic, force popular science wave)

The animation principles

Because of the high refresh rate, and the visual retention effect of the human eye, understanding how animation works is very simple. The essence of painting is to let the human eye see the visual effect of the change caused by the refresh of the image, and the change should be carried out in a coherent and smooth way. If you come in, you can see a continuous animation in our browser

Disadvantages of timers

You probably already know that the timer can be animated, but it is used to change the position or value of the element to quickly play the static image, thus forming a complete animation

However, due to the timer in JS execution, it has some small flaws, although can endure, but there are better things out, why not eliminate him?

We know that the timer is not fixed. This is because JS is a single-threaded language, it must use asynchronous, to solve some need to delay the execution of the problem, so why say timer execution time is not fixed? That’s where polling comes in

Event Loop

Event Loop is a kind of operation mechanism of computer system. The JavaScript language uses this mechanism to solve some of the problems associated with single-threaded running.

In JavaScript, tasks are divided into two types: macrotasks, also known as tasks, and microtasks.

Common macro tasks include: Script entire code, setTimeout, setInterval, setImmediate (IE10), I/O, AND UI Rendering.

Common microtasks include process. nextTick (Node only), Promise, Object.observe(deprecated), and MutationObserver

Let’s briefly learn the execution process of Event Loop

First of all,
then

Finally, the microtask is completed, the stack is cleared, and the content of the next Event Loop in the queue is retrieved. At the beginning of the execution, you will find that when the timer is executed, there is a pile of synchronization code in front of it, which also takes time. If there is a Loop in front of it for three or five hundred times, it will be a waste of time. This exposes a disadvantage of timers: frame loss phenomenon, that is, each interval is actually uncertain, resulting in a mismatch with the browser refresh rate, may appear frame loss phenomenon! (Later corrected by the boss, the timer only lost frames because the browser policy is not interfered, not blocked by the synchronization task)

RequestAnimationFrame (() => console.log())"Hello World"));
      while (true);
   
Copy the code

After looking at the process, please carefully understand the above picture, there will be a harvest!

What is requestAnimationFrame?

RequestAnimationFrame is HTML 5 provides a special request for animation API, as its name implies is request animation frames, he is encapsulated in the host object, window. RequestAnimationFrame () telling the browser – you want to perform an animation, And requires the browser to call the specified callback function to update the animation before the next redraw. This method takes as an argument a callback function that is executed before the browser’s next redraw

What are the benefits of requestAnimationFrame?

  • RequestAnimationFrame collects all DOM operations in each frame in a single redraw or reflow that closely tracks the browser refresh rate, which is typically 60 frames per second.
  • RequestAnimationFrame will not be redrawn or reflow in hidden or invisible elements, which of course means less CPU, GPU and memory usage.

How does requestAnimationFrame work?

//html
  <div id="a"></div>
  //js
    <script>
      var e = document.getElementById("a");
      var flag = true;
      var left = 0;

      function render() {
        if (flag == true) {
          if (left >= 100) {
            flag = false;
          }
          e.innerHTML = left++;
        } else {
          if (left <= 0) {
            flag = true; } e.innerHTML = left--; / /}}setInterval(function () {
      //   render();
      // }, 1000);
      (function animloop() { render(); var a=window.requestAnimationFrame(animloop); }) ();Copy the code

That’s where it ends, but suddenly the question arises, how does he stop?

Executing a function to put back an ID 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.

/ / window. CancelAnimationFrame (a) pay attention to this to write inside the function body,Copy the code

conclusion

This is the end of the requestAnimationFrame exploration, because I am also learning while writing, wrong, please correct!

RequestAnimationFrame In detail