正文
很多项目里的防抖节流都是复制粘贴的老代码 ,存在内存泄漏、频繁触发、异常卡顿等问题。今天给大家一套生产可用、无 bug 的实现。
1. 防抖(debounce)
js
function debounce(fn, delay = 300) {
let timer = null
return function (...args) {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
适用场景:
- 搜索框输入
- 窗口 resize
- 表单实时验证
2. 节流(throttle)
js
function throttle(fn, delay = 300) {
let lastTime = 0
return function (...args) {
const now = Date.now()
if (now - lastTime >= delay) {
lastTime = now
fn.apply(this, args)
}
}
}
适用场景:
- 滚动加载
- 鼠标移动
- 高频点击
3. 常见错误
- 不清除定时器导致内存泄漏
- 频繁创建新函数导致不生效
- 在 React/Vue 中每次渲染都重新生成
最佳实践
在 Vue 中:
js
const handleInput = debounce((val) => {
// 请求
}, 300)
在 React 中:
js
const handleScroll = useCallback(throttle(() => {}, 300), [])
个人观点 · 仅供参考