防抖确保最后一次触发后延时执行,节流保证函数至少间隔指定时间执行;二者均返回带cancel方法的新函数,防抖支持immediate选项,节流提供flush方法。

防抖(Debounce)和节流(Throttle)是处理高频事件(如 resize、scroll、input)的核心技巧。写成通用的高阶函数,关键在于:**接收原函数 + 配置参数 → 返回新函数,内部维护状态并按策略执行**。下面给出简洁、可复用、带取消能力的标准实现。
通用防抖高阶函数(支持立即执行与手动取消)
防抖保证「最后一次触发后等待 delay 毫秒,期间无新触发才执行」;加 immediate: true 可改为首次立即执行、后续进入等待期。
返回的函数自带 .cancel() 方法,用于主动清空待执行定时器:
function debounce(fn, delay, options = {}) {
const { immediate = false } = options;
let timerId = null;
<p>const debounced = function (...args) {
if (timerId !== null) {
clearTimeout(timerId);
}</p><pre class="brush:php;toolbar:false;">if (immediate && timerId === null) {
fn.apply(this, args);
}
timerId = setTimeout(() => {
if (!immediate) {
fn.apply(this, args);
}
timerId = null;
}, delay);};
debounced.cancel = function () { if (timerId !== null) { clearTimeout(timerId); timerId = null; } };
return debounced; }
通用节流高阶函数(时间戳版,更精准)
节流确保「函数至少间隔 delay 毫秒才执行一次」。时间戳版比定时器版更可靠(避免定时器堆积或漏触发),适合 scroll/resize 等连续事件。
同样提供 .cancel()(清空上一次记录的时间戳)和 .flush()(立即执行一次,重置计时):
function throttle(fn, delay) {
let lastTime = 0;
<p>const throttled = function (...args) {
const now = Date.now();
if (now - lastTime >= delay) {
fn.apply(this, args);
lastTime = now;
}
};</p><p>throttled.cancel = function () {
lastTime = 0;
};</p><p>throttled.flush = function (...args) {
if (Date.now() - lastTime >= delay) {
fn.apply(this, args);
lastTime = Date.now();
}
};</p><p>return throttled;
}</p>使用示例与注意事项
- 防抖常用于搜索框输入(等用户停顿再请求):
const search = debounce(fetchSuggestions, 300); input.addEventListener('input', search); - 节流适合监听滚动位置(如懒加载):
const handleScroll = throttle(updatePosition, 100); window.addEventListener('scroll', handleScroll); - 注意
this和参数传递:所有实现都用fn.apply(this, args)正确绑定上下文和参数 - 若需兼容旧浏览器,
Date.now()可替换为+new Date();setTimeout已广泛支持 - 不建议在防抖/节流函数内直接操作 DOM 或触发副作用——应封装纯逻辑,保持可测试性
进阶提示:组合与类型安全(TypeScript 可选)
如果项目用 TypeScript,可为两个函数添加泛型,自动推导入参与返回值类型:
function debounce<t extends any> any>(
fn: T,
delay: number,
options?: { immediate?: boolean }
): T & { cancel(): void } { /* ... */ }</t>这样调用时保留原始函数签名,编辑器能正确提示参数和返回值,减少运行时错误。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











