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我

  • 相关阅读:
    [转]html之file标签 --- 图片上传前预览 -- FileReader
    常用正则表达式
    c# color 颜色代码
    WebForm 母版页使用
    iframe同域自适应问题
    完整版AJAX
    AJAX基础
    jQuery 小特效【文本框折叠隐藏,展开显示】【下拉菜单】【颜色渐变】【弹窗+遮罩】
    JQuery中的Dom操作和事件
    LINQ 【增、删、改、查】数据绑定
  • 原文地址:https://www.cnblogs.com/lisiyang/p/11585553.html
Copyright © 2011-2022 走看看