Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use HTML5 timer

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use HTML5 timer, the article is very detailed, has a certain reference value, interested friends must read it!

Preface

Timer has always been the core technology of javascript animation. The key to writing an animation loop is to know how long the delay is appropriate. On the one hand, the loop interval must be short enough to make different animation effects appear smooth and smooth; on the other hand, the loop interval must be long enough to ensure that the browser is able to render the resulting changes.

Most computer monitors refresh at 60Hz, which is equivalent to redrawing 60 times per second. Most browsers limit the redraw operation to no more than the monitor redraw frequency, because even beyond that frequency, the user experience will not be improved. Therefore, the best cycle interval for the smoothest animation is 1000ms/60, which is approximately equal to 16.6ms.

The problem with setTimeout and setInterval is that they are not accurate. Their inherent running mechanism determines that the interval parameter actually specifies the amount of time to add animation code to the browser UI thread queue to wait for execution. If other tasks have been added in front of the queue, the animation code will wait until the previous task is completed.

RequestAnimationFrame uses the system time interval to maintain the best rendering efficiency, which will not cause excessive rendering and increase overhead because the interval time is too short; nor will it be because the interval time is too long, the use of animation card is not smooth, so that a variety of web page animation effects can have a unified refresh mechanism, so as to save system resources, improve system performance, and improve visual effects.

Characteristics

RequestAnimationFrame aggregates all DOM operations in each frame and completes it in a single redraw or reflow, and the interval between redrawing or reflux closely follows the refresh rate of the browser.

In hidden or invisible elements, requestAnimationFrame will not redraw or reflow, which of course means less CPU, GPU, and memory usage.

RequestAnimationFrame is an API specially provided by the browser for animation. At run time, the browser will automatically optimize the method call, and if the page is not active, the animation will be automatically paused, effectively saving CPU overhead.

Usage

The requestAnimationFrame method takes a callback as an argument, and the callback function is passed in a parameter, DOMHighResTimeStamp, indicating when the callback function currently sorted by requestAnimationFrame () is triggered. The return value is a request ID that represents the unique identity in the callback list. You can pass this value to window.cancelAnimationFrame () to cancel the callback function.

RequestID = window.requestAnimationFrame (callback)

With this api, you can put some code to be executed on the next re-rendering, avoiding triggering a large number of reflow in a short period of time.

For example, the callback function of the page scrolling event (scroll) is suitable for using this api, delaying the callback operation until the next re-rendering. However, it should be noted that requestAnimationFrame does not manage callback functions, that is, calling requestAnimationFrame with the same callback function multiple times before the callback is executed will cause the callback to be executed multiple times in the same frame. In the simplest way, you can use the throttling function to solve this problem, or you can find a way to make there is only one callback function in the requestAnimationFrame queue:

Let scheduledAnimationFrame = false;document.body.onscroll = () = > {if (scheduledAnimationFrame) return; scheduledAnimationFrame = true; window.requestAnimationFrame (() = > {scheduledAnimationFrame = false; / / do something});}

Of course, the best application scenario is in frame animation, which can greatly optimize performance.

Interview questions

How to render tens of thousands of pieces of data does not jam the interface.

This question examines how to render data without jamming the page, that is, you can not render tens of thousands of pieces at a time, but should render part of the DOM at a time, so you can refresh every 16 ms through requestAnimationFrame.

Document control setTimeout (() = > {/ / insert 100, 000 data const total = 100000 / / insert 20 data at a time. If you think the performance is not good, reduce const once = 20 / / render data a total of several times const loopCount = total / once let countOfRender = 0 let ul = document.querySelector ("ul") Function add () {/ / optimizes performance. Insertion does not cause reflux const fragment = document.createDocumentFragment (); for (let I = 0; I < once; iTunes +) {const li = document.createElement ("li"); li.innerText = Math.floor (Math.random () * total); fragment.appendChild (li);} ul.appendChild (fragment) CountOfRender + = 1; loop ();} function loop () {if (countOfRender < loopCount) {window.requestAnimationFrame (add);}} loop ();}, 0)

Compatibility

Some old browsers do not support this api. In order to use this api, you can customize this method and mount it under window:

(function () {var lastTime = 0; var vendors = ['webkit',' moz']; 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 (! window.requestAnimationFrame) window.requestAnimationFrame = function (callback) {var currTime = new Date () .getTime (); var timeToCall = Math.max (0,16-(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);};} ()); above is all the content of the article "how to use HTML5 timer". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report