节流

  • 时间戳:频繁触发事件时,第一次会立即执行

function throttle(fn, interval) {
    // 上一次执行的时间
    let last = 0
    return function () {
        let now = Date.now()
        if (now - last >= interval) {
            fn.apply(this, arguments)
            last = Date.now()
        }
    }
}

function handle() {
    console.log(Date.now());
}

const throttleHandle = throttle(handle, 10)

throttleHandle()
throttleHandle()
throttleHandle()
throttleHandle()
  • 定时器:第一次和最后一次都会延时执行

      function throttle(fn, interval) {
        let timer = null;
        return function () {
          let context = this;
          let arg = arguments;
          if (!timer) {
            timer = setTimeout(function () {
              fn.apply(context, arg);
              timer = null;
            }, interval);
          }
        };
      }

      function handle() {
        console.log(Math.random());
      }
      const throttleHandle = throttle(handle, 1000);
      throttleHandle();
      throttleHandle();
      throttleHandle();
      throttleHandle();
  •  时间戳和定时器相结合

function throttle(fn, delay) {
    let timer = null
    // 开始时间
    let startTime = Date.now()
    return function () {
        // 当前时间
        let curTime = Date.now()
        // 剩余时间
        let remaining = delay - (curTime - startTime)
        clearTimeout(timer)
        if (remaining <= 0) {
            fn.apply(this,arguments)
            startTime=Date.now()
        }else{
            timer=setTimeout(fn, remaining);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值