前端性能优化之防抖-debounce

这周接到一个需求-给输入框做模糊匹配。这还不简单,监听input事件,取到输入值去调接口不就行了? 然而后端小哥说不行,这个接口的数据量非常大,这种方式调用接口的频率太高,而且用户输入时调用根本没有必要,只要在用户停止输入的那一刻切调接口就行了。 唉?这个场景听起来怎么这么像防抖呢?

那到底什么是防抖呢? 大家一定见过那种左右两边中间放广告位的网站,在网页滚动时,广告位要保持在屏幕中间,就要不断地去计算位置,如果不做限制,在视觉上广告位就像在“抖”。防止这种情况,就叫防抖了!

防抖的原理是什么? 我一直觉得网上流传的例子非常形象:当我们在乘电梯时,如果这时有人过来,我们会出于礼貌一直按着开门按钮等待,等到这人进电梯了,刚准备关门时,发现又有人过来了!我们又要重复之前的操作,如果电梯空间无限大的话,我们就要一直等待了。。。当然人的耐心是有限的!所以我们规定了一个时间,比如10秒,如果10秒都没人来的话,就关电梯门。

用专业术语概括就是:在一定时间间隔内函数被触发多次,但只执行最后一次。

最简易版的代码实现:

function debounce(fn, delay) {
    let timer = null;

    return function() {
        const context = this;
        const args = arguments;

        if (timer) {
            clearTimeout(timer);
            timer = null;
        }

        timer = setTimeout(() => {
            fn.apply(context, args);
        }, delay);
    };
}
复制代码

fn是要进行防抖的函数,delay是设定的延时,debounce返回一个匿名函数,形成闭包,内部维护了一个私有变量timer。我们一直会触发的是这个返回的匿名函数,定时器会返回一个Id值赋给timer,如果在delay时间间隔内,匿名函数再次被触发,定时器都会被清除,然后重新开始计时。

当然简易版肯定不能满足日常的需求,比如可能需要第一次立即执行的,所以要稍做改动:

function debounce(fn, delay, immediate) {
    let timer = null;

    return function() {
        const context = this;
        const args = arguments;

        timer && clearTimeout(timer);

        if(immediate) {
            const doNow = !timer;

            timer = setTimeout(() => {
                timer = null;
            }, delay);

            doNow && fn.apply(context, args);
        }
        else {
            timer = setTimeout(() => {
                fn.apply(context, args);
            }, delay);
        }
    };
}
复制代码

比起简易版,多了个参数immediate来区分是否需要立即执行。其它与简易版几乎一致的逻辑,除了判断立即执行的地方:

const doNow = !timer;

timer = setTimeout(() => {
    timer = null;
}, delay);

doNow && fn.apply(context, args);
复制代码

doNow变量的值为!timer,只有!timer为true的情况下,才会执行fn函数。第一次执行时,timer的初始值为null,所以会立即执行fn。接下来非第一次执行的情况下,等待delay时间后才能再次触发执行fn。 注意!与简易版的区别,简易版是一定时间多次内触发,执行最后一次。而立即执行版是不会执行最后一次的,需要再次触发。

防抖的函数可能是有返回值,我们也要做兼容:

function debounce(fn, delay, immediate) {
    let timer = null;

    return function() {
        const context = this;
        const args = arguments;
        let result = undefined;

        timer && clearTimeout(timer);

        if (immediate) {
            const doNow = !timer;

            timer = setTimeout(() => {
                timer = null;
            }, delay);
            
            if (doNow) {
                result = fn.apply(context, args);
            } 
        }
        else {
            timer = setTimeout(() => {
                fn.apply(context, args);
            }, delay);
        }

        return result;
    };
}
复制代码

但是这个实现方式有个缺点,因为除了第一次立即执行,其它情况都是在定时器中执行的,也就是异步执行,返回值会是undefined。

考虑到异步,我们也可以返回Promise:

function debounce(fn, delay, immediate) {
    let timer = null;

    return function() {
        const context = this;
        const args = arguments;

        return new Promise((resolve, reject) => {
            timer && clearTimeout(timer);

            if (immediate) {
                const doNow = !timer;

                timer = setTimeout(() => {
                    timer = null;
                }, delay);

                doNow && resolve(fn.apply(context, args));
            }
            else {
                timer = setTimeout(() => {
                    resolve(fn.apply(context, args));
                }, delay);
            }
        });
    };
}
复制代码

如此,只要fn被执行,那必定可以拿到返回值!这也是防抖的终极版了!

猜你喜欢

转载自juejin.im/post/5be693d16fb9a04a053f2f1c