JS-function anti-shake and function throttling

1. Function anti-shake: The callback will be executed after the event is triggered n seconds. If it is triggered again within this n seconds, the timer will be re-timed.

function debounce(fun,delay) {
    return function(){
        let that = this;
        let args = arguments;
        clearTimeout(fun.timerId);
        fun.timerId  = setTimeout(function(){
            fun.apply(that, args);
        }, delay);
    }
}

function ajax(){...}
let ajaxDebounce = debounce(ajax, 500);
inputA.addEventListener('keyup', function(e){
    ajaxDebounce(e.target.value);
});

2. Function throttling: It is stipulated that a function can only be triggered once in a unit time. If multiple functions are triggered in this unit time, it will only take effect once.

function throttle(fun, delay) {
    let last, deferTimer;
    return function() {
        let that = this;
        let args = arguments;
        let now = +new Date();
        if(last && last < now + delay) {
            clearTimerout(deferTimer);
            deferTimer = setTimeout(function(){
                last = now;
                fun.apply(that, args);
            }, delay);
        }else{
            last = now;
            fun.apply(that, args);
        }
    }
}

function ajax(){...}
let ajaxThrottle = throttle(ajax, 500);
inputA.addEventListener('keyup', function(e){
    ajaxThrottle(e.target.value);
});

 

Published 35 original articles · won praise 1 · views 6718

Guess you like

Origin blog.csdn.net/qq_36162529/article/details/103299917