JavaScript常用技巧之函数节流

上一篇文章写了写关于防抖的东西,与之相关的节流当然也要来聊一聊。

在固定时间内,多次触发只执行一次。

类似于定时执行的概念,显然通过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日常学习之节流

上述代码的完整代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值