防抖函数(Debounce)
场景:限制函数频繁触发,只有最后一次操作结束后,函数才执行。例如输入框搜索、窗口缩放事件等。
/**
* 防抖函数
* @param {Function} fn - 需要防抖的函数
* @param {number} delay - 延迟时间,单位毫秒
* @param {boolean} immediate - 是否立即执行一次(默认false)
* @returns {Function}
*/
function debounce(fn, delay = 300, immediate = false) {
let timer = null;
return function (...args) {
const context = this;
if (timer) clearTimeout(timer);
if (immediate) {
const callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, delay);
if (callNow) fn.apply(context, args);
} else {
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
}
};
}
// 用法示例
const onResize = debounce(() => {
console.log('窗口大小
订阅专栏 解锁全文
2万+



被折叠的 条评论
为什么被折叠?



