延迟判断算法

  |  
 阅读次数

延迟判断算法

延迟判断 为了 降低 [vue,react] 框架中的, [onChange,click…] 事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/** 组件内,函数外 缓存状态 */
this.state = {
cacheValueArr: []
};

/** 核心思想是:
* 先缓存一次数据,
* 定时器 2S 后 再缓存一次数据
* 对比判断 值 是否 相等,代表没有改变
*/
onChange(e) {
let cacheArr = this.state.cacheValueArr; // 先引用缓存的状态
let len = cacheArr.push(e); // push方法 会返回 长度,改变原数组
let lastOne = cacheArr.slice(-1); // 数组最后一位的 值

setTimeout(() => {
let lastLen = this.state.cacheValueArr.length; // 2S 后再缓存 长度有无变化
let lastOnes = this.state.cacheValueArr.slice(-1); // 2S 后再缓存 值有无变化
if (len === lastLen) {
this.setState({
curE: e
})
debugger
}
}, 2000);
}
````

# 函数防抖动

/**

  • Created by hjl on 2017/8/15.
    */
    var throttle = function (func, interval) {
    var self = func,
    timer,
    firstTime = true;

    return function () {
    var args = arguments,
    me = this;
    if (firstTime) {
    self.apply(me, args);
    return firstTime = false;
    }
    if (timer) {
    return false;
    }

    timer = setTimeout(function () {
    clearTimeout(timer);
    timer = null;
    self.apply(me, args);
    }, interval || 3000);
    };
    };

    1
    2

    **借鉴方法**

    /**

    • 函数防抖
      *
    • @param {any} method 方法名
      */
      function debounce(method) {
      clearTimeout(method.tId);
      method.tId = setTimeout(function() {
      method.call();
      }, 200);
      }
      ````