Image stabilization

Scenario: Events are triggered multiple times, such as mouse movement or search box focus, but the callback function is executed only after the last event is triggered.

User triggers an event – Checks whether there is a timer – yes – Clears the original timer – Sets a new timer – Executes the callback after the timer

                                                               |__________no________________|

function debounce(fn,delay){
    var timer = null;
    return function(){
        var that = this;
        var args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function(){
            fn.apply(tha,args);
            },delay||500)
    }
}
Copy the code

The throttle

Scenario: For example, click the submit form event, the user will trigger the event multiple times, only take the first event, within a period of time after the trigger events do not take effect.

User trigger event – Check whether there is a timer – yes – End

| _______no_______ set new timer – execute callback – after emptying the timer

function throttle(fn,delay){ var timer = null; return function (){ if(timer){return false} var that = this; var args = arguments; fn.apply(that,args); timer = setTimerout(function(){ clearTimeout(timer) timer = null; },delay||500); }}Copy the code

References:

Understand throttling & anti-shaking

Interviewer: Please talk about functions throttling and anti-shaking