# 解题思路 or 实现原理

  • Lodash

创建一个节流函数, 在 wait 秒内最多执行func一次的函数。该函数提供一个 cancel 方法取消延迟的函数调用以及 flush方法立即调用。

  • Ours

规定一个时间 wait, wait 秒内,将触发的事件合并为一次并执行。

throttle

# 实现代码

/*
 * @Author: Rainy
 * @Date: 2020-01-02 18:31:50
 * @LastEditors  : Rainy
 * @LastEditTime : 2020-01-02 19:58:10
 */

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

export function _throttle(
  callback: WithParamsReturnAnyFunction,
  wait: number = 300,
  options: ObjectMap<any> = {},
): WithParamsReturnAnyFunction {
  let last: number = 0;
  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 throttle = () => {
    let params: any = arguments
    let now = +new Date();

    if (leading) {
      timer = setTimeout(() => {
        timer = null;
      }, wait);
      // @ts-ignore
      result = !timer && callback && callback.apply(this, params);
    } else {
      if (last && now < last + wait) {
        clearTimeout(timer);

        timer = setTimeout(() => {
          last = now;

          // @ts-ignore
          result = callback && callback.apply(this, params)
        }, wait);
      } else {
        last = now;

        // @ts-ignore
        result = callback && callback.apply(this, params)
      }
    }
    return result;
  }

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

  return throttle;
}
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
53
54
55
56
57
58
59
60
61
62

# 参考资料

Debouncing and Throttling Explained Through Examples (opens new window)