关于javascript:实现debounce和throttle函数

1.该函数间断调用时,闲暇工夫必须大于或等于函数定义的wait工夫,工作才会执行的函数叫防抖(debounce)函数
2.该函数间断调用时,每隔一段时间,至少执行一次工作的函数叫节流(throttle)函数。

这里模仿lodash的防抖函数 _.debounce(func, [wait=0], [options=]) ,先说下lodash防抖函数的入参options的配置项:

options.leading 与|或 options.trailing 决定提早前后如何触发(注:是 先调用后期待 还是 先期待后调用)。 func 调用时会传入最初一次提供给 debounced(防抖动)函数 的参数。 后续调用的 debounced(防抖动)函数返回是最初一次 func 调用的后果。
留神: 如果 leading 和 trailing 选项为 true, 则 func 容许 trailing 形式调用的条件为: 在 wait 期间屡次调用防抖办法。

简略点说lodash的防抖函数,当options.leading为true、options.trailing为false时,就要咱们平时所须要应用的节流函数用法,当options.leading为false、options.trailing为true时就是咱们平时所须要应用的防抖函数用法,自己本人模仿实现了一下,代码如下

/**
 * 
 * @param {function} func 须要执行的防抖函数
 * @param {number} wait 等待时间毫秒
 * @param {object} options {leading: 为true示意在等待时间开始前执行防抖函数,trailing: 为true示意在等待时间开始之后执行防抖函数}
 */
function debounce(func, wait = 500, options) {
    if (typeof func !== "function") throw new Error("func must be function");

    let timer = null;
    const {
        leading = false,
        trailing = true
    } = options || {}

    const res = function (...argus) {
        const self = this;

        if (!leading && trailing) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(self, argus);
                timer = null;
            }, wait)
        }

        if (leading){
            if (!timer) {
                func.apply(self, argus);
                timer = setTimeout(() => {
                    timer = null
                }, wait)
            } else {
                // 如果存在定时器,阐明在wait时间段内执行过防抖函数
                if (trailing){
                    // 如果为true,则期待wait工夫后执行防抖函数
                    clearTimeout(timer);
                    timer = setTimeout(() => {
                        func.apply(self, argus);
                        timer = null
                    }, wait)
                }
            }

        }
        
        // 设置防抖函数的后置勾销性能
        res.cancel = function () {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
        }

        // 设置防抖函数立刻执行性能
        res.flush = function () {
            if (timer) {
                clearTimeout(timer);
                timer = null;
                func.apply(self, argus);
            }
        }
    }

    return res;
}

这里特地留神,自己编写的内置cancel、flush办法只对options.leading=false和options.trailing=true时无效,对于其余状况下临时还没做逻辑判断解决,如各位小伙伴理解其它规定机制,能够给自己点意见,哈哈哈!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理