防抖节流.md
防抖
javascript
function debounce(fn, delay) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}节流
javascript
function throttle(fn, delay) {
let canRun = true;
return function () {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, delay);
};
}示例
js
function handleScroll() {
console.log("scrolling...");
}
const debouncedHandleScroll = debounce(handleScroll, 1000);
window.addEventListener("scroll", debouncedHandleScroll);