认识
2024年03月12日
一、认识
防抖(debounce
) 是一种限制函数调用频率的技术, 其基本思路是在连续触发事件时,只在最后一次触发后经过一定的等待时间才真正执行函数,避免因高频触发导致的性能问题。防抖(debounce
) 实现原理: 通过一个变量(通常称为 timer
)来保存 setTimeout
返回的定时器标识。当连续事件不断触发时, 每次都会重置定时器, 重新计时, 只有在事件停止触发一段时间(即 wait
毫秒后)后, 定时器的回调才会执行, 从而调用目标函数。
二、实现
function debounce(fn, wait, immediate) {
let timer = null;
return function (...args) {
if (timer) {
clearTimeout(timer);
}
if (!timer && immediate) {
fn.apply(this, args);
}
timer = setTimeout(() => {
timer = null;
if (!immediate) {
fn.apply(this, args);
}
}, wait);
};
}