函数防抖和节流 区别及实现方式

概念:
函数防抖(debounce):触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。

函数节流(throttle):高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率。

函数节流(throttle)与 函数防抖(debounce)都是为了限制函数的执行频次,以优化函数触发频率过高导致的响应速度跟不上触发频率,出现延迟,假死或卡顿的现象。
防抖:

function debounce(fn, delay=1000) {
    let timer = null;
    return function() {
        const args = arguments,
          that = this;
        clearTimeout(timer);
        timer = setTimeout(()=> {
            fn.apply(that, args)              
        }, delay)
    }
}
function test() {
    console.log(Math.random())
}
window.addEventListener('scroll', debounce(test, 2000));

节流

function throttle1(fn, delay=200) {
    let timer = null;
    let lastTime;
    return function() {
        let args = arguments,
          that = this,
          nowTime = Date.now();
        if (lastTime && nowTime - lastTime < delay) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                lastTime = nowTime;
                fn.apply(that, args);
            }, delay)
        } else {
            lastTime = nowTime;
            fn.apply(that, args);
        }
    }
}

//节流throttle代码:
function throttle(fn,delay) {
    let canRun = true; // 通过闭包保存一个标记
    let timer = null;
    return function () {
        let args = arguments,
          that = this;
         // 在函数开头判断标记是否为true,不为true则return
        if (!canRun) return;
         // 立即设置为false
        canRun = false;
        clearTimeout(timer);
        // 将外部传入的函数的执行放在setTimeout中
        timer = setTimeout(() => { 
        // 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
        // 当定时器没有执行的时候标记永远是false,在开头被return掉
            fn.apply(that, args);
            canRun = true;
        }, delay);
    };
}
function test() {
    console.log(Date.now())
}
window.addEventListener('scroll', throttle(test, 200));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值