throttle(func, wait)
每 wait 毫秒内最多只调用一次 func。
搜索框输入时的实时联想。
监听 scroll 事件计算位置信息。

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}debounce(func, wait)
自最近一次触发后延迟 wait 毫秒调用 func。
注册时输入完用户名后检测是否被占用。
监听 resize 事件计算尺寸信息。

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}