函数的防抖与节流处理

函数的防抖:

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我

 

posted @ 2019-09-25 16:24  饭饭大人  阅读(450)  评论(0编辑  收藏  举报