防抖与节流
约 263 字小于 1 分钟
布欧-Lewyon
2026-05-16
首页 › JavaScript › 进阶实践 › 防抖与节流
防抖(Debounce)
在连续触发的事件中,只有最后一次触发后等待指定时间才执行。
function debounce(fn, delay = 300) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// 使用:搜索框输入
const searchInput = document.querySelector('#search');
searchInput.addEventListener('input', debounce(async (e) => {
const results = await fetch(`/api/search?q=${e.target.value}`);
// 渲染结果...
}, 300));节流(Throttle)
在连续触发的事件中,每隔指定时间执行一次。
function throttle(fn, interval = 200) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= interval) {
lastTime = now;
fn.apply(this, args);
}
};
}
// 使用:滚动事件
window.addEventListener('scroll', throttle(() => {
console.log('滚动位置:', window.scrollY);
// 加载更多数据...
}, 200));对比
| 场景 | 防抖 | 节流 |
|---|---|---|
| 搜索输入 | ✅ 输入停止后才搜索 | ❌ |
| 滚动加载 | ❌ | ✅ 定期检查位置 |
| 窗口 resize | ✅ 调整完成后执行 | ✅ 定期执行 |
| 按钮点击 | ✅ 防止重复提交 | ❌ |
