防抖和节流

53 阅读1分钟

防抖:debounce

防抖指一定时间内,再次触发该事件,会清空上次事件重新计时,如果制定的时间内没有再次触发,才会执行。

应用场景

input输入时,我们等用户输入停止100ms后再去请求服务端接口

//debounce 是 多次点击,一段时间内,点击后会重新计时,只触发一次。
export function debounce(fn, delay) {
    let timer = null;
    return function () {
        let this_ = this;
        let args = [...arguments];
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(this_, args);
            clearTimeout(timer);
        }, delay)
    }
}
//立即执行
export function debounce_immediate(fn, delay) {
    let timer = null;
    let immediate = true;
    return function () {
        let this_ = this;
        let args = [...arguments];
        if (timer) {
            clearTimeout(timer);
        }
        if (immediate) {
            fn.apply(this_, args);
            immediate = false;
        } else {
            timer = setTimeout(() => {
                fn.apply(this_, args);
                clearTimeout(timer);
                immediate =true; // 如果希望 过了 单位时间后, 再次点击都可以立即执行可以在此处设置为true
            }, delay)
        }
    }
}

节流 throttle

节流指的是,一段时间只会触发一次该事件,稀释执行频率 滚动时,我们希望一段时间内只触发一次滚动事件。

    export function throttle(fn, delay) {
    let pre = 0;
    return function () {
        let this_ = this;
        let args = [...arguments];
        let now = new Date();
        if (now - pre >= delay) {
            fn.apply(this_, args);
            pre = now;
        }
    }
}

export function throttle_timeout(fn, delay) {
   
    let timer = null;
    return function () {
        let this_ = this;
        let args = [...arguments];
        if(timer) return;
        if(!timer){
            fn.call(this_,...args);
        timer =setTimeout(()=>{
            timer = null;
        },delay)
    }
    }
}