说说对防抖节流的理解
# 是什么
- 防抖: n秒后执行某事件,若在n秒内重复触发,重新计时n秒后执行
- 节流: n秒后执行某事件,若在n秒内重复触发,只执行一次
# 触发场景
- resize
- scroll
- mousemove
- keypress
# 防抖 debounce
function debounce(fn, wait){
let timer
return function (){
clearTimeout(timer)
const context = this || {}
const args = [...arguments]
timer = setTimeout(() => {
fn.apply(context, args)
}, wait);
}
}
# 节流
function throttle(fn, wait){
let timer
return function(){
if(!timer){
const context = this || {}
const args = [...arguments]
timer = setTimeout(() => {
fn.apply(context, args)
timer = null
}, wait);
}
}
}
# 区别
# 共同点
- 都是基于setTimeout实现
- 都是降低执行频率,节省资源
# 不同点
- 防抖是停止触发后多久执行一次
- 节流是没隔多少秒执行一次
# 应用场景
# 防抖
- 搜索框输入
- 手机号、邮箱验证
- 窗口resize调整
# 节流
- 滚动加载
- 搜索框联想
上次更新: 2021/12/19, 18:05:42