防抖(Debounce)
概念:
防抖的核心思想是,在事件被触发的一段时间内,如果再次触发,则重新计时。只有在指定的时间间隔内没有再次触发事件时,才会执行目标函数。换句话说,防抖会等待用户“停下来”后再执行。
适用场景:
- 搜索框输入建议。
- 窗口调整大小后的布局计算。
- 表单验证。
实现代码:
function debounce(fn, delay) {
let timer = null; // 定时器变量
return function (...args) {
const context = this;
// 清除之前的定时器
if (timer) clearTimeout(timer);
// 设置新的定时器
timer = setTimeout(() => {
fn.apply(context, args); // 执行目标函数
}, delay);
};
}
示例使用:
const handleResize = () => console.log('Window resized!');
const debouncedHandleResize = debounce(handleResize, 500);
window.addEventListener('resize', debouncedHandleResize);
节流(Throttle)
概念:
节流的核心思想是,在一定时间间隔内,无论事件触发多少次,目标函数最多只会执行一次。换句话说,节流会在指定的时间段内“锁定”函数的执行。
适用场景:
- 滚动事件监听。
- 鼠标移动事件监听。
- 高频点击按钮防止多次提交。
实现代码:
function throttle(fn, interval) {
let lastTime = 0; // 上次执行的时间戳
return function (...args) {
const context = this;
const now = Date.now(); // 当前时间戳
// 如果当前时间与上次执行时间的差值大于等于设定的间隔
if (now - lastTime >= interval) {
lastTime = now; // 更新上次执行时间
fn.apply(context, args); // 执行目标函数
}
};
}
示例使用:
const handleScroll = () => console.log('User scrolled!');
const throttledHandleScroll = throttle(handleScroll, 1000);
window.addEventListener('scroll', throttledHandleScroll);
总结对比:
| 特性 | 防抖(Debounce) | 节流(Throttle) |
|---|---|---|
| 触发条件 | 在事件停止触发后的一段时间内执行一次 | 在固定时间间隔内最多执行一次 |
| 适用场景 | 用户操作结束后触发(如搜索、调整大小) | 高频连续触发的场景(如滚动、鼠标移动) |
| 核心思想 | 延迟执行,等待事件“冷却” | 限制执行频率,确保间隔时间 |

1万+

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



