(防抖)debounce和(节流)throttle

85 阅读1分钟

什么是防抖和节流?
debounce: 假设我们设置一个时间间隔n,我们在n的时间间隔里不停触发事件,那这个事件就永远不会执行,当我们停止触发后,从停止触发的时间往后加n的时间执行一次函数即可 throttle:假设我们设置一个时间间隔n,我们在n的时间间隔里不停的触发事件,这时候事件只会以n的时间单位触发一次事件

防抖的使用场景有哪些呢?
1.文字输入校验
2.高频次事件触发,最终只需要一次结果的函数
...

节流的使用场景有哪些呢?
1.scroll
2.resize
...

debounce实现

/**
* handle 最终执行的函数
* wait  触发事件后多久执行
* immediate 是执行第一次,还是最后一次,默认执行最后一次
*/
function myDebounce(handle, wait = 300, immediate = false) {
    let timer = null;
    return function(...args) {
        const self = this;
        // 当需要执行第一次时,就是立即执行,那后面的定时器也不需要开启了
        let bool = immediate && !timer;
        //  当需要执行第一次且timer不存在
        bool ?  handle.call(self, ...args) : null;
        clearTimeout(timer);
        timer = setTimeout(() => {
            //  判断immediate值,true就不需要执行函数
            !immediate ? handle.call(self, ...args): null;
            timer = null
        }, wait);

    }
}

throttle实现

 function throttle(handle, wait = 300) {
    let initTime = new Date();
    let timer = null;
    return function proxy(...args) {
        const now = new Date();
        const self = this;
        const delta = wait - (now - initTime);
        // 小于等于0说明是低频操作,可以立即执行函数
        // 为啥要加else...if因为在这个时间差内有可能多次执行函数,这时候我们只用执行一次
        if (delta <= 0) {
            handle.apply(self, args);
            clearTimeout(timer);
            timer = null;
            initTime = new Date();
        } else if (!timer) {
            timer = setTimeout(() => {
                clearTimeout(timer);
                timer = null;
                handle.apply(self, args);
                initTime = new Date();
            }, delta);
        }
    }
}