函数的防抖与节流处理

本文详细介绍了JavaScript中函数的防抖(debounce)与节流(throttle)技术的应用及实现原理,包括如何通过这两种技术优化用户体验,提高系统性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数的防抖:

1 防抖: 触发N秒后,执行,或在N秒内一直触发,则重新计时,使用场景比如 input onchange事件

1 该方法为 延时执行的防抖
debounce = (func, delay) => {// 防抖 触发后 N秒才执行 如果在N秒内又出发, 则重新计时 主要用于 search let id = null; return function (args) { args.persist(); let that = this, _args = args; clearTimeout(id); id = setTimeout(function () { func.call(that,_args); }, delay); } }
2 该方法为 立即执行的防抖
debounce = (func, delay) => {// 防抖 触发后 N秒才执行 如果在N秒内又出发, 则重新计时 主要用于 search
    let id = null;
    return function (args) {
      args.persist(); 
      let that = this, _args = args;
      if(id) clearTimeout(id);
      let callnow = !id;
      id = setTimeout(function () { 
                          i        d = null;
                              }, delay); 
       } 
      if(callnow) fun.apply(that,_args)
  }            

函数的节流:

  _throttle = (func, delay) => {// 节流 规定一个时间内 只能处触发一次,如果规定时间内多次触发 ,只有第一次生效
    // 时间戳 
    let time =  Date.now();
    return function(args){
      args.persist(); 
      let that = this, _args = args;
      let now = Date.now();
      if(now - time > delay) {
        func.call(that,_args);
        time =  Date.now();
      }
    }
}
_throttle = () => {
       //  定时器 
    // let id = this.id, th = this;
    // return function(args){
    //   let that = this, _args = args;
    //   // 不能用id=null 来判断  因为每次setstate都会重新 设置id=null
    //   let bol = !id;
    //   if(bol) {func.call(that,_args);}
    //   if(!th.id) th.id = setTimeout(function(){
    //     th.id = null;
    //     id = null;
    //   },delay)
    // }  
}

 

 遇到的坑

在写节流的时候,如果使用定时器方式的节流,并使用了react 代码如下

<input onChange={this._throttle(this.change,1000)}>
如果 change方法内部 setState 方法,那么要注意 每一次setstate都会重新 执行 this._throttle方法
所以throttle的id 我绑定的是react内部的this.id,不能直接用闭包的id去做,否则会失效。

有问题call我

 

转载于:https://www.cnblogs.com/lisiyang/p/11585553.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值