A window. RequestIdleCallback

1. :

This method will call the function queue at the browser’s idle time. So that we can make the operator in the main event loop and low priority work performed on the background, and the delay does not affect the key events, such as the animation and input response, function is usually carried out in accordance with the advanced first order of execution call, but if set the timeout (timeout execution time), will lead to in order to perform the corresponding function operation before timeout and disrupted execution order.

2. Usage

window.requestIdleCallback(callback,option)

Parameters:

Callback: A function reference to be called when the browser is idle receives a parameter called IdleDeadline, which gets the status of the current idle time and whether the callback has been executed before the timeout. IdleDeadline objects include didTimeout, which is a Boolean value indicating whether the task has timed out; And timeRemaining(), which represents the timeRemaining in the current frame, and is the time for task execution. Option: configuration item. Timeout can be configured. If timeout is specified with a positive value, and the callback has not been invoked by timeout milliseconds, the callback will be enforced in the next idle period, although this will most likely have a negative impact on performance.

The return value:

An ID, you can through the window. CancelIdleCallback () to end the callback

requestIdleCallback(myNonEssentialWork, { timeout: 2000 }); / / task queue const tasks = [() = > {the console. The log (" the first task ");}, () = > {the console. The log (" the second task ");}, () = > {the console. The log (" the third task "); },]; Function myNonEssentialWork (deadline) {// If the frame has an extra time, Or the timeout while ((deadline. TimeRemaining () > 0 | | deadline. DidTimeout) && tasks. The length > 0) {work (); } if (tasks.length > 0) requestIdleCallback(myNonEssentialWork); } function work () { tasks.shift()(); Console. log(' Execute task '); }Copy the code

3. Use setTimeout to simulate implementation

window.requestIdleCallback = window.requestIdleCallback || function(handler) { let startTime = Date.now(); return setTimeout(function() { handler({ didTimeout: false, timeRemaining: Function () {return math.max (0, 50.0 - (date.now () -starttime)); function() {return math.max (0, 50.0 - (date.now () -starttime)); }}); }, 1); }Copy the code

When you can perform tasks in RIC, note the following:

1. Perform recalculation instead of emergency tasks

2. Idle callback execution time should be less than 50ms, preferably less

3. Do not operate DOM in the idle callback, because it is to use the gap idle time after the reshoot and redraw, re-operation of DOM will cause the reshoot and redraw, DOM operation is recommended to be carried out in rAF. At the same time, the time required to manipulate the DOM is uncertain because it leads to recalculation of the layout and drawing of the view, so such operations are not predictable.

4.Promise is not recommended to do this either, because the higher-priority microtask in the Event Loop, the Promise callback property, will be executed immediately after the requestIdleCallback ends, regardless of whether there is any spare time. This has a high probability of making a frame over 16 ms. React time sharding is implemented based on requestIdleCallback. However, due to RIC compatibility and 50ms smoothness issues, React has a home-made implementation called Scheduler

2. Windows. RequestAnimationFrame

1. :

Notifies the browser that the specified callback function is invoked to update the animation before the next redraw. Redrawn if you want to in the next update before the next frame animation, you need to the callback function itself must once again call window. RequestAnimationFrame (), when the window. The requestAnimationFrame running hidden iframe label or in the background, Will be paused to improve performance

2. Usage

window.requestAnimationFrame(callback)

Callback: The function called to update the animation frame before the next redraw. The callback function is passed the DOMHighResTimeStamp parameter, which represents the time at which the callback function starts execution

Return value: an ID, can be introduced into the window. The cancelAnimationFrame () to cancel the callback function.

Added 3.

In the past, we used setTimeout and setInterval to execute animation. The drawback of this method is that the execution time of callback function is not fixed, and it may be stuck at the end or no longer executed, resulting in frame loss and lag

The root cause of this problem is timing, when the browser needs to know when to respond to the callback function. SetTimeout or setInterval uses a timer to trigger a callback function. However, a timer cannot be guaranteed to execute correctly. There are many factors that affect its running time, such as: When a synchronous code is executed, the system waits until the synchronous code is finished and there are no other tasks in the asynchronous queue. Also, we know that the optimal time for each re-render is about 16.6ms. If the timer interval is too short, it will cause overrendering and increase overhead. Too long will delay rendering and make the animation not smooth.

RequestAnimationFrame differs from setTimeout or setInterval in that it is up to the system to determine when the callback should be executed, asking the browser to execute the callback before the next rendering. Regardless of the refresh rate of the device, the requestAnimationFrame interval follows the time it takes to refresh the screen once; For example, if the refresh rate of a device is 75 Hz, then the time interval is 13.3 ms (1 second / 75 times). Note that this method ensures that the callback function is rendered only once per frame, but if there are too many tasks in that frame, it will still cause a lag. Therefore, it can only ensure that the minimum interval between rerenders is the screen refresh time.