# js函数防抖和节流
# 1、函数防抖
指触发事件后 n 秒后才执行函数,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
// 防抖
function debounce(fn, delay = 500) {
let timer;
return function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
// 用法
var c = 30;
function test(a, b) {
console.log(a, b, c);
}
const d = debounce(test);
d(1, 2);
setTimeout(() => {
d(3, 4);
}, 100);
// 3 4 30
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
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
# 2、函数节流
连续触发事件但是在 n 秒中只执行一次函数。
// 节流
function throttle(fn, delay = 500) {
let timer;
return function() {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
}
};
}
// 用法
var c = 30;
function test(a, b) {
console.log(a, b, c);
}
const d = throttle(test);
d(1, 2);
setTimeout(() => {
d(3, 4);
}, 100);
// 1 2 30
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25