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
| // 防抖函数
| function debounce(func, delay, immediate = false) {
| let timer = null;
| return function () {
| const context = this;
| const args = arguments;
|
| const callNow = immediate && !timer;
| // 如果定时器已经存在,清除它
| if (timer) {
| clearTimeout(timer);
| }
|
| // 设置一个新的定时器
| timer = setTimeout(() => {
| if (!immediate) {
| func.apply(context, args);
| }
| timer = null;
| }, delay);
|
| // 配置立即执行
| if(callNow) {
| func.apply(context, args)
| }
| };
| }
|
|