# 常用工具函数
# 给scroll
,resize
等高频触发事件节流
/*
@params
fn 节流的函数
interval 函数执行的间隔时间
*/
function throttle(fn, interval) {
let prevTimer;
let now = Date.now();
return function() {
if (!prevTimer) {
prevTimer = now;
}
if (now - prevTimer > interval) {
fn.apply(this, arguments);
prevTimer = now;
}
};
}
// window 为浏览器全局对象
window.onscroll = throttle(() => {
// 这里最少每隔100ms才会执行
}, 100);
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
# 给浏览器 DOMinput
事件防抖
function debounce(fn, delay) {
let timer;
return function() {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
// 假设`input`为文本输入框DOM节点
input.oninput = debounce(() => {
// 100ms内这里只会执行一次
}, 100);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
← 操作数组常用方法