实现节流防抖函数

节流

1. 基本概念

throttle(func, wait)

每 wait 毫秒内最多只调用一次 func。

2. 应用场景

  • 搜索框输入时的实时联想。

  • 监听 scroll 事件计算位置信息。

3. 流程图

节流

4. 编写代码

1function throttle(func, wait) {
2  let lastTime = 0;
3  let timer = null;
4
5  return function () {
6    if (timer) {
7      clearTimeout(timer);
8      timer = null;
9    }
10
11    let self = this;
12    let args = arguments;
13    let nowTime = +new Date();
14
15    const remainWaitTime = wait - (nowTime - lastTime);
16
17    if (remainWaitTime <= 0) {
18      lastTime = nowTime;
19      func.apply(self, args);
20    } else {
21      timer = setTimeout(function () {
22        lastTime = +new Date();
23        func.apply(self, args);
24        timer = null;
25      }, remainWaitTime);
26    }
27  };
28}

防抖

1. 基本概念

debounce(func, wait)

自最近一次触发后延迟 wait 毫秒调用 func。

2. 应用场景

  • 注册时输入完用户名后检测是否被占用。

  • 监听 resize 事件计算尺寸信息。

3. 流程图

防抖

4. 编写代码

1function debounce(func, wait) {
2  let timer = null;
3
4  return function () {
5    if (timer) {
6      clearTimeout(timer);
7      timer = null;
8    }
9
10    let self = this;
11    let args = arguments;
12
13    timer = setTimeout(function () {
14      func.apply(self, args);
15      timer = null;
16    }, wait);
17  };
18}