This article was published by Barbara Jr

Introduced 0.

Here’s an example:

Simulate ajax query request after input in the input box, without adding the effect of anti-shake and throttling, attached here is the complete executable code:

<! DOCTYPE HTML >< HTML lang="en"> <head> <meta charset="UTF-8"> <title> <title> <style type="text/ CSS "></style> <script Type ="text/javascript"> window.onload = function () {function ajax(content) {console.log(' Ajax request '+  content) } let inputNormal = document.getElementById('normal'); inputNormal.addEventListener('keyup', function (e) { ajax(e.target.value) }) } </script> </head> <body> <div> 1. </div> </body> </ HTML >Copy the code

Effect: Type one in the input box and an “Ajax request” (in this case console) is triggered.

Disadvantages: waste request resources, can be added to optimize the tremble and throttling.

This article will introduce what are anti-shake and throttling respectively, their application scenarios, and implementation methods. Both anti-vibration and throttling are designed to solve performance problems caused by a large number of functions being triggered in a short period of time, such as high trigger frequency resulting in a response speed that cannot keep up with the trigger frequency, delays, false death, or stalling. However, they address different business requirements, so the principles of implementation are different. Let’s look at the details below.

1. Debounce

1.1 What is Anti-shake

Execute the callback function n seconds after the event is triggered. If it is triggered again within n seconds, the timer is reset.

1.2 Application Scenarios

(1) After the user continuously enters a string of characters in the input box, only the last query Ajax request will be executed after the input, which can effectively reduce the number of requests and save request resources;

(2) Window resize, scroll events, constantly adjust the size of the browser window, or the corresponding event will be triggered when scrolling, so that it can only trigger once;

1.3 implementation

Or the above example, here to add anti-shake to optimize, the complete code is as follows:

<! DOCTYPE HTML >< HTML lang="en"> <head> <meta charset=" utF-8 ">< title Type ="text/javascript"> window.onload = function () {function ajax(content) {console.log(' Ajax request '+  content) } function debounce(fun, Delay) {return function (args) {return function (args) {let that = this let _args = args ClearTimeout (fun.id) fun.id = setTimeout(function () {fun.call(that, _args)}, delay) } } let inputDebounce = document.getElementById('debounce') let debounceAjax = debounce(ajax, 500) inputDebounce.addEventListener('keyup', function (e) { debounceAjax(e.target.value) }) } </script> </head> <body> <div> 2. <input type="text" name="debounce" id="debounce"> </div> </body> </ HTML >Copy the code

Code description:

1. Each time an event is triggered, the current timer is cleared and the timeout call is reset, i.e. the timer is reset. This causes each high frequency event to cancel the previous timeout call, causing the event handler not to fire;

2. Only when the high-frequency event stops, the timeout call triggered by the last event can be executed after the delay time.

Effect:

With the addition of anti-shake, a request will not be sent if the input box is continuously typed, but only if the input is not repeated within a specified period of time. If you stop typing first, but enter again within a specified interval, the timing is retriggered.

2. Throttle

2.1 What is Throttling

Specify a unit of time. Within this unit of time, only one callback function that triggers an event can be executed. If an event is triggered multiple times within the same unit of time, only one callback function can take effect.

2.2 Application Scenarios

(1) The mouse continuously triggers an event (such as clicking), only triggering once per unit of time;

(2) In the infinite loading scenario of the page, the user should send ajax requests every once in a while while scrolling the page, rather than request data when the user stops scrolling the page;

(3) Monitor rolling events, such as whether to slide to the bottom to automatically load more, and throttle to judge;

2.3 implementation

Again, add throttling here to optimize, the complete code is as follows:

<! DOCTYPE HTML >< HTML lang="en"> <head> <meta charset="UTF-8"> <title> Add throttle </title> <style type="text/ CSS "></style> <script Type ="text/javascript"> window.onload = function () {function ajax(content) {console.log(' Ajax request '+  content) } function throttle(fun, delay) { let last, deferTimer return function (args) { let that = this; let _args = arguments; let now = +new Date(); if (last && now < last + delay) { clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fun.apply(that, _args); }, delay) } else { last = now; fun.apply(that, _args); } } } let throttleAjax = throttle(ajax, 1000) let inputThrottle = document.getElementById('throttle') inputThrottle.addEventListener('keyup', function (e) { throttleAjax(e.target.value) }) } </script> </head> <body> <div> 3. <input type="text" name="throttle" id="throttle"> </div> </body>Copy the code

Effect: Experiments show that the setup in the code is installed while typing continuously, executing ajax requests every 1 second

3. Summary

Summarize the difference between anti-shake and throttling:

Effect:

Function stabilization is executed only once in a certain period of time; Function throttling is executed at intervals, ensuring that no matter how frequently an event is fired, a real event handler will be executed within a specified period of time.

– principle:

Anti-shake is to maintain a timer that is specified to trigger the function after the delay time. However, if triggered again within the delay time, the current timer will be cleared and the timeout call will be reset, that is, the timer will be reset. In this way, only the last operation can be triggered.

Throttling triggers a function by determining whether a certain time has been reached. If it has not, a timer is used to delay it. The next event will reset the timer.

If you have any questions, please point out.

This article has been authorized by the author to Tencent Cloud + community, more original text pleaseClick on the

Search concern public number “cloud plus community”, the first time to obtain technical dry goods, after concern reply 1024 send you a technical course gift package!