In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "JavaScript throttling and anti-shake case analysis", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "JavaScript throttling and anti-shake case analysis" bar!
1. Js anti-shaking and throttling
In the window resize, scroll, output box content check and other manipulation, if the frequency of event handling function calls is unlimited, it will increase the burden on the browser, resulting in a very poor user experience. Then for the optimization of front-end performance and for a better user experience, we can use anti-shake (debounce) and throttling (throttle) to achieve this effect and reduce the frequency of calls.
Second, why scrolling scroll, window resize and other events need to be optimized
Scrolling events are frequently used: lazy loading of pictures, automatic loading of data by sliding, floating navigation bar on the side, etc.
When binding scroll, resize events, but when it occurs, it is triggered at a very high frequency and at close intervals. In the daily development of the page, the browser will get stuck if a large number of location calculations, DOM operations, element redrawing, and so on involved in the event cannot be completed before the next scroll event starts.
Third, the relationship between scrolling and front-end performance optimization of page rendering
Why does scrolling need optimization? The event mentioned earlier involves a large number of location calculations, DOM operations, element redrawing, and so on, which are related to the rendering of the page, which is related to the performance optimization of the front end. Like nesting dolls, one layer is covered with one layer, each layer is closely connected, and each layer is so ordinary and important.
Review the rendering and optimization of the front end
When a web page is generated, it will be Layout+Paint at least once. In the process of user access, users will continue to rearrange (reflow) and redraw (repaint). User scroll behavior and resize behavior will lead to continuous re-rendering of the page, and frequent intervals, easy to cause browser card frames.
Fourth, anti-shake Debounce1 anti-shake Debounce scenario
Some scenarios in ① trigger events too frequently (mousemove onkeydown onkeyup onscroll)
If the ② callback function is executed too frequently, there will also be stutters. You can trigger and remove useless operations after a period of time
2 anti-shaking principle
It must not be executed until n seconds after the event is triggered. If the event is triggered within n seconds of an event, the time of the new event prevails, it will be executed after n seconds, and the event will not be triggered until the event is triggered within n seconds.
Official explanation: when the event is triggered continuously, the event handler will only execute once if the event is not triggered within a certain period of time. If the event is triggered again before the set time, the delay will be resumed.
3 simple implementation of anti-shake function / / simple anti-shake function function debounce (func, wait, immediate) {/ / timer variable var timeout; return function () {/ / each time scrolle is triggered, the timer clearTimeout (timeout) is cleared first; / / specify the number of seconds before triggering the event operation handler timeout = setTimeout (func, wait) };}; / / handler function handlerFunc () {console.log ('Success') bound to the scrolle event;} / / does not use anti-jitter window.addEventListener (' scroll', handlerFunc); / / uses anti-jitter window.addEventListener ('scrolle', debounce (handlerFunc, 1000)) 4 the evolution process of anti-shake function ① this event binding problem / / returns a function in the form of closure, which internally solves the problem of this pointing and the problem of event object transmission function debounce (func, wait) {var timeout; return function () {var context = this; var args = arguments ClearTimeout (timeout) timeout = setTimeout (function () {func.apply (context, args)}, wait);} ② immediately triggers the problem / / triggers execution for the first time, and starts to execute the anti-shake function after it is triggered again / / you do not have to repeat this function when you use it. Only the function returned by itself has the anti-shake function function debounce (func, wait, immediate) {var timeout; return function () {var context = this; var args = arguments; if (timeout) clearTimeout (timeout). / / whether to execute if (immediate) {var callNow =! timeout; timeout = setTimeout (function () {timeout = null; func.apply (context, args) immediate = true;}, wait) for the first time in a batch of events If (callNow) {func.apply (context, args)} immediate = false;} else {timeout = setTimeout (function () {func.apply (context, args); immediate = true;}, wait) } ③ return value problem function debounce (func, wait, immediate) {var timeout, result; return function () {var context = this, args = arguments; if (timeout) clearTimeout (timeout); if (immediate) {var callNow =! timeout Timeout = setTimeout (function () {result = func.apply (context, args)}, wait); if (callNow) result = func.apply (context, args);} else {timeout = setTimeout (function () {result = func.apply (context, args)}, wait);} return result }} ④ cancel anti-shake, add cancel method function debounce (func, wait, immediate) {var timeout, result; function debounced () {var context = this, args = arguments; if (timeout) clearTimeout (timeout); if (immediate) {var callNow =! timeout Timeout = setTimeout (function () {result = func.apply (context, args)}, wait); if (callNow) result = func.apply (context, args);} else {timeout = setTimeout (function () {result = func.apply (context, args)}, wait);} return result } debounced.cancel = function () {cleatTimeout (timeout); timeout = null;} return debounced;} V. Throttling Throttle1 throttling Throttle scenario
① pictures loaded lazily
② ajax data request load
2 throttling principle
If the event continues to be triggered, the function is executed only at regular intervals.
Official explanation: when an event is triggered continuously, it is guaranteed that the event handler will only be called once in a certain period of time.
3 throttling implementation-timestamp and timer
Time stamp
Var throttle = function (func, delay) {var prev = Date.now () return function () {var context = this; var args = arguments; var now = Date.now (); if (now-prev > = delay) {func.apply (context, args); prev = Date.now () }} function handle () {console.log (Math.random ());} window.addEventListener ('scroll', throttle (handle, 1000))
Timer
Var throttle = function (func, delay) {var timer = null; return function () {var context = this; var args = arguments; if (! timer) {timer = setTimeout (function () {func.apply (context, args); timer = null;}, delay) } function handle () {console.log (Math.random ());} window.addEventListener ('scroll', throttle (handle, 1000)) 4 the evolution of the throttle function ① timestamp triggers / / when it starts to trigger, it will be executed immediately If the wait value is not exceeded for the last time, function throttle (func, wait) {var context, args; var previous = 0; / / the initial point in time and critical point in time return function () {var now = + new Date (); context = this; args = arguments; if (now-previous > wait) {func.apply (context, args) Previous = now;}} ② timer triggers / / will not be executed immediately for the first time, but will be executed the last time, complementary to the timestamp. Function throttle (func, wait) {var context, args, timeout; return function () {context = this; args = arguments; if (! timeout) {timeout = setTimeout (function () {func.apply (context, args); timeout = null;}, wait) } ③ combines timestamp with timer function throttle (func, wait) {var timer = null; var startTime = Date.now (); return function () {var curTime = Date.now (); var remaining = wait- (curTime-startTime); var context = this; var args = arguments; clearTimeout (timer); if (remaining)
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.