JS防抖与节流

防抖

在设定的时间内触发一次事件,会在设定的时间结束之后执行该事件处理程序,如果在设定的时间内多次触发事件,则每次触发事件都会重新计时。

简单理解就是:单位时间内,频繁触发一个事件,只执行最后一次。

  const inputElement = document.querySelector('.inputElement')
  inputElement.oninput = debounce(getData, 500)
  
  function debounce(fn, delay){ // 通过闭包来封装节流函数
    let timer = null
    return function(){
      if(timer){
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn.call(this)
      }, delay);
    }
  }

  function getData(){ // 模拟请求数据
    setTimeout(()=>{
     console.log(`请求数据:${this.value}`);
    }, 200)
  }

节流

在设定的时间内触发一次事件,会在设定的时间结束之后执行该事件处理程序,在设定的时间内多次触发事件,只会在设定的时间结束后执行一次。

简单理解就是:单位时间内,频繁触发一个事件,减少执行次数。

window.onscroll = throttle(getData, 500)

function throttle(fn, delay){ // 封装节流函数
  let flag = true
  return function($event){
    if(flag){
      setTimeout(() => {
        fn($event)
        flag = true
      }, delay)
    }
    flag = false
  }
}

function getData(e){
  console.log(e) // 模拟业务逻辑
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值