手写系列之JavaScript
wen 2022/9/23 手写系列
# 1. 节流、防抖
// throttle
function throttle(fn, delay = 200) {
let timer = null;
return function () {
if (timer) {
return;
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
}
}
const div = document.getElementById('div');
div.addEventListener('drag', throttle(function (e) {
console.log(e.offsetX, e.offsetY);
}));
// debounce
function debounce(fn, delay = 500) {
// timer 是闭包中的
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
}
}
const input = document.getElementById('input');
input.addEventListener('keyup', debounce((e) => {
console.log(e.target);
console.log(input1.value);
}, 1000));
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
36
37
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
36
37