“This is the second day of my participation in the August More Text Challenge.
Principle of animation: the computer refreshes every 16.7ms, so it looks like smooth movement due to the visual stay of the human eye.
Screen refresh frequency: the number of images appearing on the screen per second (60Hz for a common laptop).
There are many ways to realize animation effects, such as timer in Javascript, Transition and animation in CSS3, and Canvas in HTML5. Html5 also provides an API for requesting animations, requestAnimationFrame (requestAnimationFrame).
grammar
window.requestAnimationFrame(callback);
Copy the code
If you want to update the next frame before the browser redraws, the callback itself must call requestAnimationFrame() again.
parameter
-
callback
-
The function called to update the animation frame before the next redraw (the above callback function). 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.
-
Multiple callback functions in the same frame will each receive the same timestamp, even if some time has elapsed during the calculation of the workload for the previous callback function. The timestamp is a decimal number in milliseconds with a minimum accuracy of 1ms(1000μs). Be sure to always calculate the time interval between each call using the first parameter (or some other method to get the current time), otherwise animations will run faster on screens with high refresh rates.
The return value
A long integer, the request ID, 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.
sample
const element = document.getElementById('some-element-you-want-to-animate');
let start;
function step(timestamp) {
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(The ${Math.min(0.1 * elapsed, 200)}px)`;
if (elapsed < 2000) {
// Stop animation after two seconds
window.requestAnimationFrame(step); }}window.requestAnimationFrame(step);
Copy the code
Disadvantages of setTimeout implementation
By setting the interval time to constantly change the image position, to achieve the animation effect. However, it is easy to catch and shake. The reason is:
- The setTimeout task is put into an asynchronous queue, and the task in the queue will be executed only after the main thread task is finished. Therefore, the actual execution time is always later than the settime.
- The fixed interval of setTimeout may not be the same as the screen refresh time, causing frame loss.
RequestAnimationFrame advantage
The system determines when the callback function is executed. If the refresh frequency is 60Hz, the callback function will be executed at each refresh interval without frame loss or stalling
CPU energy saving: When using setTimeout to achieve animation, when the page is hidden or minimized, setTimeout is still performing animation tasks in the background, because the page is not visible or unavailable at this time, refreshing animation is meaningless, it is a complete waste of CPU resources. RequestAnimationFrame is completely different. When a page is running in a background TAB or hidden
Function throttling: In high frequency events (resize, Scroll, etc.), to prevent multiple function executions in a refresh interval, requestAnimationFrame is used to ensure that functions are executed only once in each refresh interval. This ensures smooth performance and saves function execution costs.
Graceful degradation
Due to compatibility problems, you need to degrade the interface encapsulation, use advanced features in preference, and roll back the interface based on browser conditions until only setTimeout can be used.