节流与防抖
2023-02-26 21:02:00
节流
节流函数:在指定时间内只执行一次
throttle.js
function throttle(fn, delay) {
let timer = null;
return function (...args) {
if (timer) return;
timer = setTimeout(() => {
fn.apply(this, ...args);
timer = null;
}, delay);
};
}
防抖
防抖函数:在指定时间内只执行最后一次
debounce.js
function debounce(fn, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, ...args);
}, delay);
};
}