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 realize the Anti-shaking and throttling of JavaScript

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the JavaScript anti-shake and throttling how to achieve the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this JavaScript anti-shaking and throttling how to achieve the article will have a harvest, let's take a look.

1. Preface

First of all, let's give an example. Baidu home page of the Baidu input box, when users enter, each time the input information, we can see Baidu server returned to us the Lenovo keyword. Every time we change a word, it changes the association word, which is the speed that we can see with the naked eye. In fact, if we don't deal with it, we may have made dozens of requests for the same keyword association on the server. The specific speed depends on the running speed of different pc and other machines. Well, as we just mentioned, for the same keyword, there are so many requests that you may want to present to the user only once, and the rest of the requests are wasted, and if thousands or even hundreds of millions of users request at the same time, the burden on the server is huge.

Problems solved by anti-jitter and throttling:

In continuously triggered events, frequent calls to event handlers will increase the performance burden on the browser or server, resulting in a poor user experience. What are the continuously triggered events?

For example, the scrolling event of the browser scroll bar, the resize event of the browser window adjustment, the content verification of the input box, and the touchmove event on the mobile side, and so on.

Therefore, we will use anti-shake function (debounce) and throttle function (throttle) to limit the frequency of event handler calls.

In general: the anti-shake function (debounce) and the throttle function (throttle) control the number of times the function is executed on the timeline.

two。 Function anti-shake (debounce) delay anti-shake

Delay anti-shake (debounce): a callback is performed n seconds after the event is triggered, and if it is triggered again within that n seconds, the time is re-timed.

Example of life: if someone enters the elevator (trigger event), the elevator will leave in 10 seconds (execute the event listener), and then if someone enters the elevator (triggers the event again in 10 seconds), we have to wait another 10 seconds to start again (rescheduling).

When the event is triggered continuously, the event handler will only execute once if the event is not triggered for a certain period of time.

If the event is triggered again before the set time comes, the delay starts again.

As shown in the figure below, when the click event is continuously triggered, the handle function is not executed. When the click event is not triggered within 1000 milliseconds, the click event is triggered with a delay.

Front edge anti-shaking

The action is executed first, and then the cycle is set, during which events are triggered, the action is not performed, and the cycle is reset.

Why are you doing this?

Imagine the first kind of delayed debounce, we originally wanted to reduce the frequency of initiating request associations for the keywords entered by the user, but if the user keeps typing in the time we set, the result is that the user can't see the keyword all the time, we might as well initiate a request the first time, and the server returns the result and presents it to the user, and then the subsequent user's typing ends in continuing the request).

Anti-shaking. I'm anti-shaking! Function handle () {console.log ("Anti-shaking success!") ;} _ window.onload = function () {/ / 1. Get the button and bind the event var myDebounce = document.getElementById ('debounce1'); myDebounce.addEventListener (' click',debounce (handle,1000,true));} / / Anti-shake function function debounce (fn,wait, immediate) {/ / 2. Set the timestamp, use setTimeout to delay the let timer execution of the return function, result; return function (. Args) {/ / 3. Timer exists, clear the function in the timer if (timer) clearTimeout (timer) / / 4.1 immediately execute the return function if (immediate) {if (! timer) {result = fn.apply (this,args);} timer = setTimeout (() = > {timer = null;}, wait) } else {/ / 4.2 not immediately execute the return function timer = setTimeout (() = > {fn.apply (this,args);}, wait);}} / / 5. Returns the return value of the function return result;} when executed immediately

Achieve results:

Principle analysis:

The function of anti-shake function, which returns after delaying the packaging of the incoming function.

Before the previous execution of the setTimeout, the second trigger will overwrite the previous timer and perform the second function.

The previous time due to asynchronous delay has not been completed, use clearTimeout to clear the previous timer, cancel the last fn function

To keep the this pointing inside the fn, use apply to change the this pointing

Fn is passed as a function, not a function call

Anti-shake function to achieve summary function debounce (fn,wait, immediate) {/ / 2. Set the timestamp and use setTimeout to delay the execution of the return function let timer, result; return function (... args) {/ / 3. Timer exists, clear the function in the timer if (timer) clearTimeout (timer); / / 4.1 immediately execute the return function if (immediate) {if (! timer) {result = fn.apply (this,args) } timer = setTimeout (() = > {timer = null;}, wait);} else {/ / 4.2 not immediately execute the return function timer = setTimeout (() = > {fn.apply (this,args);}, wait);}} / / 5. When executed immediately, the return value of the function return result;} 3. Function throttling (throttling)

Throttling, the throttling strategy is to perform only one action in a fixed cycle, but not if a new event is triggered. At the end of the cycle, an event is triggered to start a new cycle. Throttling strategies are also divided into leading edge and delay.

Similar to debounce, delay refers to the execution of the action after the end of the cycle, and the leading edge refers to the start of the cycle after the execution of the action.

Throttling will dilute the execution frequency of the function.

In the process of continuously triggering an event, the function is executed immediately and every n seconds

Examples of life: we know that the current saying is that when more than 24 pictures are played continuously in one second, a continuous animation will be formed in the human vision, so in the movie playing (used to be, now do not know) is basically played at the rate of 24 per second, why not 100 or more because 24 can meet the needs of human vision, 100 will seem to be a waste of resources

Delayed throttling

Leading edge throttling

Cut costs. I'm cutting costs! Function handle () {console.log ("cut expenditure successfully!") ;} _ window.onload = function () {var myDebounce = document.getElementById ('debounce1'); myDebounce.addEventListener (' click',throttling (handle,1000,false));} / / Throttle function function throttling (fn,wait,immediate) {let timer Return function (... args) {if (! timer) {if (immediate) {fn.apply (this,args);} timer = setTimeout (() = > {if (! immediate) {fn.apply (this,args) } timer = null;}, wait);}}

Achieve results:

Throttling function to achieve a summary of throttling point I throttle! Function handle () {console.log ("cut expenditure successfully!") ;} _ window.onload = function () {var myDebounce = document.getElementById ('debounce1'); myDebounce.addEventListener (' click',throttling (handle,1000,false));} / / Throttle function function throttling (fn,wait,immediate) {let timer Return function (... args) {if (! timer) {if (immediate) {fn.apply (this,args);} timer = setTimeout (() = > {if (! immediate) {fn.apply (this,args) } timer = null;}, wait);}} 4. The difference between the two

Function throttling, no matter how often the event is triggered, ensures that a real event handler will be executed within a specified period of time.

Function anti-shake is triggered only once after the last event.

For example, in the case of unlimited loading of the page, we need the user to send an Ajax request every once in a while when scrolling the page, instead of requesting data when the user stops scrolling the page. Such a scenario is suitable to be realized by throttling technology.

5. Application scenario

For function anti-shake, there are the following application scenarios:

Add a function to the button to prevent the form from being submitted multiple times.

When AJAX is used to verify the continuous input of the input box, using the function anti-shake can effectively reduce the number of requests.

Judge whether scroll slips to the bottom, scroll event + function anti-shake

Generally speaking, it is suitable for the case of multiple events and one response.

For function throttling, there are the following scenarios:

Refresh rate in the game

DOM element drag

Canvas brush function

In general, it is suitable for a large number of events to be triggered evenly according to time.

This is the end of the article on "how to achieve anti-shaking and throttling of JavaScript". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to achieve anti-shaking and throttling of JavaScript". If you want to learn more knowledge, you are 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: 289

*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