Anti – shake and throttling are a means of performance optimization

1. Debounce

Implementation principle: When the function is triggered, the execution time is delayed first. If the function is triggered again within the delayed time, the previous delay is cancelled and a new round of delay is started again. In this way, only the last request is executed and other requests are filtered out.

In layman’s terms: an event that continues to trigger but does not execute for a certain period of time (e.g. hero returns).

Implementation idea: the first time to run the timer assigned to a variable, the second time to execute, if the interval did not exceed the timer set time will be cleared off the timer, reset the timer, in turn repeated, when stopped, did not execute the clear timer, over a certain time trigger callback function.

// fn is the function passed in. Delay is the time to pass the delay
function debounce(fn,delay){
// Set a variable, null if no timer is executed
 let timer = null;
 return function(){
 if(timer) clearTimeout(timer);
 timer = setTimeout(() = >{
// Change this to refer to the function passed in
 fn.apply(this.arguments);
// Empty the timer
 timer = null; },delay); }}Copy the code

2. Throttle

Implementation principle: When a function is triggered, it responds only to the first request within a fixed period of time. Subsequent requests are not responded until the next time period, and the function continues to respond to the first request within the next period.

In layman’s terms: continuous trigger (event) also executes, but at a lower frequency (e.g. shotgun).

The second time the function is executed, it checks whether the variable is true or not, and returns if it is true. When the first timer runs out of the function, the variable is set to flase. So the next time you judge a variable it will be flase and the functions will run in sequence.

// fn is the function passed in. Delay is the time to pass the delay
function throttle(fn,delay){
 // Set a variable, null if no timer is executed
 let timer = null;
 return function(){
 // If the timer exists, it indicates that the timer is already running. Return
 if(timer) return;
 timer = setTimeout(() = >{
 fn.apply(this.arguments);
 timer = null; },delay); }}Copy the code

Soup of the day:

Once you choose your way of life, be brave to stick it out and never return. – zola