防抖节流
防抖
function debounce(fn, delay = 50) {
let timer;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn();
}, delay);
};
}
节流
// function throttle(fn, delay = 50) {
// let timer = null;
// let flag = true;
// return function () {
// if (!flag) return;
// flag = false;
// timer = setTimeout(function () {
// flag = true;
// fn();
// clearTimeout(timer);
// }, delay);
// };
// }
function throttle(fn, delay = 50) {
let timer = null;
let lastExecTime = 0; // 上次执行时间
return function (...args) {
const now = Date.now();
const context = this;
// 计算剩余等待时间
const remaining = delay - (now - lastExecTime);
// 首次触发或超过间隔:立即执行
if (remaining <= 0 || now - lastExecTime > delay) {
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(context, args); // 立即执行
lastExecTime = now; // 更新执行时间
}
// 未到执行时间且无定时器:设置延迟执行(确保最后一次触发也执行)
else if (!timer) {
timer = setTimeout(() => {
fn.apply(context, args);
lastExecTime = Date.now(); // 更新执行时间
timer = null;
}, remaining);
}
};
}