【笔记】JS实现防抖和节流

前言

JS实现防抖和节流

防抖(Debounce)

  • 指定一个时间间隔,在时间间隔内反复触发的事件,只有最后一次会被执行,其他的事件都会被忽略
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function debounce(fn, delay) {
let lastTimer = null;
return function () {
if (lastTimer) clearTimeout(lastTimer);
lastTimer = setTimeout(() => {
fn();
lastTimer = null;
}, delay);
}
}

const handleClick = debounce(() => {
console.log("clicked");
}, 1000);

document.querySelector("#app").addEventListener("click", handleClick);

节流(Throttle)

  • 指定一个时间间隔,在时间间隔内反复触发的事件,每一次时间间隔内最多只会执行一次,其他的事件都会被忽略
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function throttle(fn, interval) {
let startTime = Date.now();
return function () {
const nowTime = Date.now();
const waitTime = interval - (nowTime - startTime);
if (waitTime <= 0) {
fn();
startTime = nowTime;
}
}
}

const handleClick = throttle(() => {
console.log("clicked");
}, 1000);

document.querySelector("#app").addEventListener("click", handleClick);

完成