关于javascript:JavaScript日常学习之节流

4次阅读

共计 1460 个字符,预计需要花费 4 分钟才能阅读完成。

上一篇文章写了写对于防抖的货色,与之相干的节流当然也要来聊一聊。

在固定工夫内,屡次触发只执行一次。

相似于定时执行的概念,显然通过 setTimeout 或者 工夫戳 都能够实现。

setTimeout

利用 setTimeout 延时执行的个性,能够在定时器执行的时候去执行事件。

function throttle(func, wait) {
    let timer;
    
    return function(...args) {if (!timer) {timer = setTimeout(() => {func.apply(this, args);
                timer = null;
            }, wait);
        }
    };
}

工夫戳

工夫戳的形式就没啥好说的了,就是计时。

function throttle(func, wait) {
    let prev = 0;
    
    return function(...args) {const now = +new Date();

        if (now - prev > wait) {func.apply(this, args);
            prev = now;
        }
    }
}

如果常常应用 lodash 的同学,可能会晓得在 lodash 的 throttle 函数中有一个 options 能够用来配置是否立刻执行、是否在进行之后再触发一次。

再回来看一下下面的两种实现形式:

  1. setTimeout:进行之后会再触发一次
  2. 工夫戳:立刻执行

那是不是能够把下面两个交融一下再加上配置,就能够了呢。

最终版

function throttle(func, wait = 0, options = {}) {const { leading, trailing} = options;
    // leading 是否立刻执行
    // trailing 是否在进行之后再执行一次
    let timer;
    let previous = leading ? 0 : +new Date();

    const callFunc = (context, args) => {func.apply(context, args);
        previous = +new Date();
        timer = null;
    }

    const throttled = function(...args) {const now = +new Date();
        // 如果 leading 是 false,那剩余时间则是 wait(第一次触发事件时)
        // 如果 leading 是 true,那剩余时间则是 wait-now < 0
        const remaining = wait - (now - previous);

        if (remaining <= 0) {if (timer) {clearTimeout(timer);
            }
            
            // 如果 remianing <= 0,则阐明间隔时间大于了 wait 秒,则执行事件
            callFunc(this, args);
        } else if (!timer && trailing) {
            // 如果还有剩余时间,则将本轮 wait 秒完结时应该执行的事件挂载到计时器上
            // 这只是为了保障在进行之后的最初一次能执行
            timer = setTimeout(() => {callFunc(this, args);
            }, remaining);
        }
    }

    // 勾销
    throttled.cancel = function() {timer && clearTimeout(timer);
        timer = null;
        previous = 0;
    };

    // 是否在 pending 状态
    throttled.pending = function() {return !!timer || (+new Date() - previous <= wait);
    }

    return throttled;
}

相干:
JavaScript 日常学习之防抖
JavaScript 日常学习之节流

上述代码的残缺代码

正文完
 0