手写源码-实现防抖函数

2021-07-12  本文已影响0人  胡小喵_
/**
 * 生成一个防抖函数
 * @param func 执行函数
 * @param wait 等待时间
 * @param immediate 是否立即执行
 */
export function debounce(func: any, wait: number = 800, immediate = false) {
    let timer: any = '';
    return function (args) {
        const _this = this;
        const _arguments = arguments;
        let res;
        if (timer) clearTimeout(timer);
        if (immediate) {
            let nowDo = !timer;
            timer = setTimeout(function () {
                timer = null;
            }, wait);
            if (nowDo) res = func.call(_this, ..._arguments);
        } else {
            timer = setTimeout(function () {
                res = func.call(_this, ..._arguments);
            }, wait);
        }
        return res;
    };
}

上一篇 下一篇

猜你喜欢

热点阅读