1. Application scenarios of anti-shake

The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset;

1. The login and SMS buttons are used to prevent users from clicking too fast and sending multiple requests

2. When adjusting the browser window size, the number of resize times is too frequent, resulting in too much calculation

3. Real-time save in the text editor, save after one second when there is no change operation

    function debounce(fn,await){
    let timer=null;
    return function(){
        let context=this;
        let args=arguments;
        if(timer){
            clearTimeout(timer)
        }
       timer= setTimeout(()=>{fn.apply(context,args)},await)
    }
}
Copy the code

2. Application scenarios of throttling

Throttling: specifies that only one function can be triggered in a unit of time. If multiple functions are triggered in a unit of time, only one function can be triggered

1. Scroll event to calculate position information every second

2. The browser plays events and calculates progress information every second

3. Input box real-time search and send request display drop-down list, send request once every second (can also do anti-shake)

function throttle(fn,await){ let prev=Date.now(); return function(){ let context=this; let args=arguments; let now=Date.now(); if((now-prev)>delay){ fn.apply(context,args); prev=Date.now(); }}}Copy the code
function throttle(fn,await){ let timer=null; return function(){ let context=this; let args=arguments; if(! timer){ timer=setTimeout(function(){ fn.apply(context,args); timer=null; },await) } } }Copy the code