1.描述
节流就是:如果你持续触发事件,每隔一段时间,只执行一次事件。
防抖是:如果你持续触发时间,触发结束后n秒执行一次事件。
2.节流
2.1 节流基本实现
function throttle(func, wait) {
let previous = 0
return function() {
let that = this
let args = arguments
let now = Date.now()
if (now - previous > wait) {
func.apply(that, args)
previous = now
}
}
}
看一下效果
这是触发就立即执行,但最后没有执行,如果想最后也执行,有头有尾呢。
2.2 有头有尾节流
function throttle(func, wait) {
let previous = 0
let timeoutId = null
return function() {
let that = this
let args = arguments
let now = Date.now()
let remain = wait - (now - previous)
if (remain <= 0 || remain > wait) {
clearTimeout(timeoutId)
timeoutId = null
func.apply(that, args)
previous = now
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
func.apply(that, args)
previous = Date.now()
}, remain)
}
}
}
2.3 有头有尾节流支持配置
function throttle(func, wait, leading=true, trailing=true) {
let previous = 0
let timeoutId = null
return function() {
let that = this
let args = arguments
let now = Date.now()
if (!previous && !leading) {
previous = now
}
let remain = wait - (now - previous)
if (remain <= 0 || remain > wait) {
clearTimeout(timeoutId)
timeoutId = null
previous = now
func.apply(that, args)
} else if (!timeoutId && trailing) {
timeoutId = setTimeout(() => {
previous = Date.now()
func.apply(that, args)
}, remain)
}
}
}
3.总结
节流和防抖都是对事件频繁触发的优化,防抖是对持续触发的事件只触发一次,而节流是间隔一段时间触发一次。