Arrangement of byte interview questions (Part 1)

The timing of browser redraw

function demo() {
    
    
  const now = Date.now();
  document.body.style.backgroundColor = 'red';
  while(Date.now() - now <= 2000) {
    
     continue; }
  document.body.style.backgroundColor = 'blue';
}

When the task of the current macro queue is not completed, the operation of turning the background red will not be redrawn, so the background here will only turn blue directly.

Asynchronous processing of addition events

function addAsync(a, b) {
    
    
  return new Promise((resolve, reject) => {
    
    
    resolve(a + b);
  })
}

const addSum = async (arrs) => {
    
    
  let asyns = [];
  while (arrs.length >= 2) {
    
    
    asyns.push(addAsync(arrs[0], arrs[1]));
    arrs.splice(0, 2);
  }
  arrs.length && asyns.push(arrs[0]);
  arrs = await Promise.all(asyns);
  if (arrs.length === 1) return arrs[0];
  else return addSum(arrs);
}

let arr = [];
for (let i = 1; i < 100; i++) arr.push(i);

addSum(arr).then(sum => console.log(sum));

The interviewer is not very satisfied with the answer. A racing mechanism needs to be added to the Promise, and an array is newly defined. In the callback of each Promise, check whether the number in the array is greater than 2, and if it is greater than 2, continue to adjust itself. Define a counter to record the number of Promises being executed. If the number in the array is 1, and the Promises are all executed, the result will be returned.

requestAnimationFrame与setTimeout

requestAnimationFrame

HTML5 new api, similar to setTimeout timer. A method of the window object window.requestAnimationFrame browser (so it can only be used in the browser) provides APIs specifically for animation, allowing dom animation and canvas animation. svg animation. There is a unified refresh mechanism for webGL animations.
Features:
1. Redraw web pages by frame. This method tells the browser that it wants to execute the animation and requests the browser to call the drop-off function to update the animation before the next redraw.
2. The system determines the execution mechanism of the callback function. The browser will automatically optimize the method call at runtime.
3. The display has a fixed refresh rate (60Hz or 75Hz), that is, it can only be redrawn 60 or 75 times per second at most. The basic idea of ​​requestAnimationFrame keeps the frequency of page redrawing in sync with this refresh rate. For example, monitor screens The refresh rate is 60Hz. Using the requestAnimationFrame API, the callback function will be executed every 1000ms / 60 ≈ 16.7ms; if the display screen refresh rate is 75Hz, the callback function will be executed every 1000ms / 75 ≈ 13.3ms.
4. The time interval of page redrawing or reflow caused by calling the callback function through requestAnimationFrame is the same as the refresh time interval of the display. So requestAnimationFrame does not need to pass the time interval like setTimeout, but the browser obtains and uses the display refresh rate through the system.

setTimeout

Continuously change the image by setting an interval time to achieve an animation effect. This method will appear stuck and jitter on some low-end machines. There are generally two reasons for this phenomenon:
1. The execution time of setTimeout is not certain. The refresh rate is affected by the screen resolution and screen size. The screen refresh rate of different devices may be different.
2.setTimeout can only set a fixed time interval. This time and the screen refresh interval may be different.
The above two situations will cause the execution pace of setTimeout and the refresh pace of the screen to be inconsistent, causing frame drop. The biggest advantage of using requestAnimationFrame to execute animation is to ensure that the callback function is executed only once in each refresh interval of the screen, so that it will not cause frame loss and animation will not freeze.

The difference between setTimeout and requestAnimationFrame

  • Engine level: setTimeout belongs to the JS engine, with event polling and event queues.
    requestAnimationFrame belongs to the GUI engine, which occurs in the redrawing and rearrangement part of the rendering process, which is consistent with the computer's resolution.
  • Performance level: When the page is hidden or minimized, the timer setTimeout is still performing animation tasks in the background.
    When the page is in an inactive state, the screen refresh task of the page will be suspended by the system, and requestAnimationFrame will also stop.
  • Application level: Use setTimeout, this timing mechanism to do animations, to simulate refreshing the page at a fixed time.
    requestAnimationFrame is an API provided by the browser specifically for animation. The browser will automatically optimize the call of the method during runtime, which can effectively save CPU overhead in a specific environment.

Guess you like

Origin blog.csdn.net/qq_40289624/article/details/111357330