函数防抖
描述:函数防抖就是在函数需要频繁触发情况时,在指定的时间间隔后,才执行一次
应用场景:检测滚动条变化 (函数节流也将利用此场景),输入框搜索
- 举例
mounted ( ) {
window.addEventListener(' scroll ', this.debounce( function ( ) {
console.log( ' hello scroll ... ' )
}, 2000 ) )
},
methods: {
debounce (fn, delay) {
let timer = null // 一打开页面,先声明 timer, 开始滑动滚动条的时候,才执行返回方法
return function () {
if (timer) clearTimeout(timer) // 将之前的 timer 清除
timer = setTimeout(() => {
fn.apply(this) // 如果滚动条不滚动的时间等于设置的delay, 那么就执行 fn 函数
}, delay)
}
},
}
函数节流
描述:函数不断触发的情况下,通过函数节流来指定函数触发的频率,比如每隔2s触发一次
解决方案 : 时间戳
- 栗子:
throttle (fn, delay) {
let last = new Date() // 一进入页面,先获取此时的时间戳
return function () { // 这里利用闭包,可以继续访问 last 的值
let now = new Date() // 滑动滚动条,将不停的获取新老时间戳
let result = now - last
console.log('result: ', result)
if (result > delay) { // 直到新的时间戳与last值只差大于指定时间间隔,将调用 fn
fn.apply(this,arguments);
last = now // 让老的时间戳等于现在的时间戳, 再隔 2s 再执行
}
}
}
综合使用(性能更佳)
结合定时器和时间戳使用
function performance(fn, delay, interval) { // 回调 , 延迟,间隔
let timer = null
let last = new Date()
return function () {
let now = new Date()
if ( timer ) clearTimeout(timer)
if ( now - last > interval ) {
fn.apply( this )
last = now
} else {
timer = setTimeout( () => {
fn.apply( this )
}, delay)
}
}
}