美文网首页
手写源码-实现防抖函数

手写源码-实现防抖函数

作者: 胡小喵_ | 来源:发表于2021-07-12 10:53 被阅读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;
    };
}

相关文章

网友评论

      本文标题:手写源码-实现防抖函数

      本文链接:https://www.haomeiwen.com/subject/fgvlpltx.html