# 解题思路 or 实现原理

  • Lodash

从上一次被调用后, 延迟 wait 毫秒后调用 func 方法。 debounced(防抖动)函数提供一个 cancel 方法取消延迟的函数调用以及 flush 方法立即调用。

  • Ours

在事件被触发 wait 秒后, 再去执行回调函数。如果 wait秒内该事件被重新触发, 则重新计时。结果就是将频繁触发的事件合并为一次, 且在最后执行。提供一个 cancel 方法取消延迟的函数调用。

debounce

# 实现代码

/*
 * @Author: Rainy
 * @Date: 2020-01-02 18:29:32
 * @LastEditors  : Rainy
 * @LastEditTime : 2020-01-02 19:57:51
 */

import { WithParamsReturnAnyFunction, ObjectMap } from 'types';
import { isAbsType } from 'utils/type';

export function _debounce(
  callback: WithParamsReturnAnyFunction,
  wait: number = 300,
  options: ObjectMap<any> = {},
): WithParamsReturnAnyFunction {
  let timer: any = null;
  let result: any = null;

  if (!isAbsType(options)) {
    throw new Error('options must be object');
  }

  const { leading = false, trailing = false, ...option } = options;

  const debounce = () => {
    const params = arguments;
    if (!!timer) {
      clearTimeout(timer);
    }

    if (leading) {
      timer = setTimeout(() => {
        timer = null;
      }, wait);

      // @ts-ignore
      result = !timer && callback && callback.apply(this, params);
    } else {
      timer = setTimeout(() => {
        // @ts-ignore
        result = callback && callback.apply(this, params);
      }, wait);
    }
  }

  debounce.cancel = () => {
    clearTimeout(timer);
    timer = null;
  }

  return debounce;
}
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

# 参考资料

Debouncing and Throttling Explained Through Examples (opens new window)