使用背景
很多时候,在浏览器的滚动操作,或者input输入框中都会经常触发某个行为, 这样也会导致浏览器卡死,或者性能下降,那么防抖就排上用场了。封装了一个防抖函数,大家可以免费参考,有好的建议可以提出。
函数名是叫做debounce, 参数方面的话是
- fn(回调函数),
- wait(等待时间),
- immediate(是否要立即执行)
`function debounce(fn, wait, immediate) {
let timeOut, result = null
let debounceType = {
debounced: function() {
if(timeOut) {
clearTimeout(timeOut)
}
const ZTHIS = this
if(immediate) {
const actionNow = !timeOut
timeOut = setTimeout(() => {
timeOut = null
}, wait)
if(actionNow) {
result = fn.apply(ZTHIS)
}
} else {
timeOut = setTimeout(() => {
result = fn.apply(ZTHIS)
}, wait)
}
return result
},
cacelDebounced: function() {
clearTimeout(timeOut)
timeOut = null
}
}
return debounceType
}
`
使用方法:
- 开启防抖:
debounce(resize, 200, true).debounced - 关闭防抖:
debounce(resize, 200, true).cacelDebounced