防抖函数和节流函数的原理应用场景

1 防抖

  1. 作用:清除前面的计时,重新计时。

  2. 原理:
    判断timer(通过闭包保存的变量),来确定是哪个setTimeout
    通过clearTimeout,阻止setTimeout中回调函数的执行,并重新执行setTimeout。

  3. 函数执行描述:debounce执行,setTimeout执行,setTimeout中回调函数还未执行时,再次执行debounce时,通过clearTimeout,阻止上次setTimeout中回调函数的执行,并重新执行setTimeout。

 let timer = 99
  function debounce(func, delay) {
     let timer = null;//创建局部变量
    return function (...args) {
      if (timer) {
        clearTimeout(timer);
        //clearTimeout(null)会出错?
      }
      console.log(timer);
      timer = setTimeout(() => {
        func.apply(this, args)}, delay
      )
    };
  }
  function add(a){
    console.log(a);

  }
  var foo = debounce(add,3000);
    console.log(timer);
    foo(4);
    
  setTimeout(()=>{
    foo(6)
  },6000)
  //99 null 4 1 6

2 节流

作用:规定时间内的重复动作无效
关键所在:

  1. 开启定时前isDelayOver 设为false
  2. fn(…args)的位置
 function throttle(fn,delay){
       let isDelayOver = true;
       return function (...args) {
         if (isDelayOver==false)
           return ;

         isDelayOver =false //关键所在:开启定时前设为false
         fn(...args)//位置
           setTimeout(()=>{
             //fn(...args)//位置
             isDelayOver = true
           },delay)

       }

    }
    let bar = throttle(add,1000)
    //
    bar(55,66)
    setTimeout(()=>{
      bar (77,88)
    },500)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值