防抖

防抖就是在规定的时间内只能触发一次函数。

  • 简易版防抖
    将多次执行变成最后一次执行。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function debounce(fn, wait = 50) {
    let timeout;
    return function (...args) {
    if (timeout) {
    clearTimeout(timeout);
    timeout = null;
    }

    timeout = setTimeout(() => {
    fn.apply(this, args);
    });
    }
    }
  • 可以立即执行的防抖

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
function debounce(fn, delay = 50, immediate = true) {
var timeout;
var time;
if (immediate) {
return function (...args) {
if (time) {
if (new Date() - time < delay) {
time = new Date();
return; // 间隔小小于上一次执行的
} else {
fn.apply(this, args);
time = new Date();
return;
}
}

if (!time) {
fn.apply(this, args);
time = new Date();
return; // 第一次立即执行
}
}
} else {
return function (...args) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}

timeout = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
}
}