In the development process, we often use scroll, Mousemove, Resize and other continuously triggered events. In this case, there is a problem. The performance of the browser is limited, and it is undoubtedly a waste to trigger these events with high frequency. Both anti-shake and throttling are ways to optimize browser performance.

Image stabilization

Anti-shake means that the event will not be executed when it is continuously triggered. The event will not be executed until the set time is reached (if the event is triggered again before the time is reached, the timing will restart). It’s like on a bus. If passengers continue to get on the bus, the driver will not drive, and when passengers stop getting on the bus, the driver will start, so as to produce the effect that a large number of triggering events will execute the function only once in a short period of time.

   function debounce(fn,wait){
       let time = null;
       return function(){
            if(!time){
              clearTimeout(time)
           };
           time = setTimeout(fn,wait);
       }
     }
              
Copy the code

The throttle

Throttling is the execution of a function only once in a certain period of time when events are fired consecutively.

function throttle(fn,wait){ let noneWorked = true; If (! noneWorked){ return false; } noneWorked = false; setTimeout(()=>{ fn() noneWorked = true},wait)Copy the code