【Vue】防抖、节流的实现

debounce:防抖,n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时
throttle:节流, n 秒内只运行一次

防抖实现:若是immediate: true的情况,需要控制timeout来使callNow在函数第一次执行和以后隔n秒后为true。对于不用立刻执行的,只需要简单setTimeout执行fn

function debounce(fn, wait, immediate) {
    let timeout;
    return function() {
        let context = this;
        if (timeout) clearTimeout(timeout); //每次新触发且旧计时未结束,重新计时
        if (immediate) { //考虑immediate:true的情况
            let callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null; //使callNow为true的条件
            }, wait);
            if (callNow) fn.apply(context, arguments);
        } else {
            timeout = setTimeout(() => {
                fn.apply(context, arguments)
            }, wait);
        }
    }
}

节流实现:设置startTime,并获取currentTime,计算是否已隔n秒。

function throttle(fn, delay) {
    let timer = null;
    let startTime = Date.now();
    return function() {
        let currentTime = Date.now();
        let remaining = delay - (currentTime - startTime);
        let context = this;
        clearTimeout(timer)
        if (remaining <= 0) {
            fn.apply(context, arguments);
            startTime = Date.now();
        } 
        else {
            timer = setTimeout(() => {
                fn.apply(context, arguments);
                startTime = Date.now();
            }, remaining);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值