zoukankan      html  css  js  c++  java
  • 函数的防抖与节流处理

    函数的防抖:

    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我

  • 相关阅读:
    检索通讯录,根据输入的电话号码的每一位下拉显示检索结果
    获取手机的具体型号 及 iOS版本号
    在iOS中使用ZBar扫描二维码
    iOS沙盒路径的查看和使用
    ios打开通讯录及点击通讯录时提取相关信息
    获取倒计时距离某一时间点的时间,判断身份证,电话号码格式是否正确的简单封装
    iOS 获取手机的型号,系统版本,软件名称,软件版本
    第三天战略会议
    第二天站略会议总结
    第一天站略会议总结
  • 原文地址:https://www.cnblogs.com/lisiyang/p/11585553.html
Copyright © 2011-2022 走看看