防抖
function debounce(fn, delay) {
let timer = null;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.call(this, ...args);
// 或者写成fn.apply(this, args);
}, delay);
};
}
function handleResize() {
console.log(111);
}
const debounceResize = debounce(handleResize, 300);
window.addEventListener("resize", debounceResize);
节流
function throttle(fn, delay) {
let lastTime = 0;
return function (...args) {
let nowTime = new Date().getTime();
if (nowTime - lastTime >= delay) {
fn.call(this, ...args);
// fn.apply(this, args);
lastTime = nowTime;
}
};
}
function handleClick() {
console.log(111);
}
const throttleClick = throttle(handleClick, 2000);
setInterval(throttleClick, 100);
在实际的开发过程中,一般会使用lodash自有的debounce函数和throttle函数对所要防抖/节流的函数进行包裹。例如
const handleClick = useCallback(
throttle(()=>{
console.log(111);
}, delay)
,[])