concept

  • Throttling Throttling means that only once is triggered for a specified period of time. For example, if we set it to 500ms, the button will only trigger once no matter how many times it is clicked within this time. The scenario could be panic buying, where there are millions of people clicking on the button quickly, which would put a lot of pressure on the server to send requests every time we click, but by throttling, we can greatly reduce the number of requests.
  • Anti-shake Anti-shake means that in a continuous operation, no matter how long the operation is performed, only a certain operation is not performed within a specified period of time, the operation is valid. In a specific scenario, you can request the server to match the search results in real time during the keyword input in the search box. If the server does not process the search results, the content in the input box keeps changing, resulting in continuous requests. If the anti-shake processing is carried out, the result is that after we complete the input content, a certain time (say 500ms) has not entered the content again, then the request will be triggered.

The following is a simple flowchart

Throttling throttle

When the callback function is triggered at a high frequency, the throttling operation causes the callback function to be executed at regular intervals.

The key is to get a function to not execute too often and to do things too quickly.

Similar to the king’s skill cooldown.

/** ** @param {*} fn is the event callback we need to wrap * @param {*} wait is the time to wait for each delayed execution */ const throttle = (fn, wait = 1500) => { let inThrottle, lastFn, lastTime; return function() { const context = this, args = arguments; if (! inThrottle) { fn.apply(context, args); lastTime = Date.now(); inThrottle = true; } else { clearTimeout(lastFn); lastFn = setTimeout(function() { if (Date.now() - lastTime >= wait) { fn.apply(context, args); lastTime = Date.now(); } }, Math.max(wait - (Date.now() - lastTime), 0)); }}; }; export default throttle;Copy the code

Stabilization debounce

When the callback function is triggered at a high frequency, the anti-shake operation makes the callback function clear the timer and start again within a certain time interval. Output the result once the timing ends.

The core is that when the same event is fired many times in a short period of time, only one callback is executed. Avoid mistaking one event for more than one.

/** ** @param {*} fn is the event callback we need to wrap * @param {*} delay is the wait time for each delayed execution */ const debounce = (fn, Delay = 1000) => {// let timer = null; Return function() {// Retain this context when called let context = this; // Retain the arguments passed in when calling let args = arguments; If (timer) {clearTimeout(timer); if (timer) {clearTimeout(timer); } function() {fn.apply(context, args); }, delay); }; }; export default debounce;Copy the code

Common Usage Scenarios

  • Listen for scroll, Mousemove and other events – throttling (calculate position every second)
  • Listen to the browser window resize operation – anti shake (only need to calculate once)
  • Verification of keyboard text input – shake proof (send a request for verification after continuous input of text, verify once is good)
  • Submit form – Anti-shake (multiple clicks to one)
  • Search search association, the user in the continuous input value, use the anti – shake to save the request resources.
  • To prevent users from clicking buttons such as login and SMS so fast that multiple requests are sent, you need to avoid shaking

Throttling and anti-shaking can be used either way. For example, to monitor page scrolling, you can throttling (start a callback every period of time) or anti-shaking (end the current scroll, continue to scroll and wait for the next trigger).

Used in the vue

index.vue

<script> import debounce from ".. /utils/debounce"; import throttle from ".. /utils/throttle"; Methods :{// static change: debounce (function () {// logic},1000) // static change: Throttle (function () {// logic},1000)} </script>Copy the code

conclusion

  • Function stabilization and function throttling both prevent frequent triggering at one time, but the two brothers work differently.
  • Function stabilization is performed only once in a certain period of time, while function throttling is performed at intervals.

Code sample