防抖节流的原理,利用setTimeout和闭包的特点访问外部函数的变量,区别在于防抖将多次操作优化成最后一次执行,例如用户输入只需校验最后输入的结果,节流则是每隔一段时间后执行一次,也是降低频率,减少多次操作的优化
防抖
function debounce(fn, delay, immediate) {
let timer = null // 外部变量
return function() {
let args = arguments
let context = this
if (immediate && !timer) { // 马上执行
fn.apply(context, args)
}
if (timer) clearTimeout(timer) // 内部访问外部变量
timer = setTimeout(() => {
fn.apply(context, args)
}, delay)
}
}
节流
function throttle(fn, delay, immediate) {
let timer = null // 外部变量
let isNow = immediate // 外部变量
return function() {
let context = this
let args = arguments
if (isNow) { //马上执行 内部访问外部变量
fn.apply(context, args)
isNow = false //内部访问外部变量
}
if (!timer) { // 不存在延时标识 内部访问外部变量
timer = setTimeout(() => {
fn.apply(context, args)
timer = null
}, delay)
}
}
}