如何使用闭包优化防抖函数?
优化之前
let timer = null
const 防抖 = (函数名, 时间, 参数) => {
clearTimeout(timer)
timer = setTimeout(() => {
函数名.call(this, ...arguments)
}, 时间)
}
const 函数名 = (函数名, 时间, 参数) => {
console.log(参数)
}
优化之后
const 防抖 = (函数名, 时间, 参数) => {
let timer = null
return function() {
clearTimeout(timer)
timer = setTimeout(() => {
函数名.call(this, ...arguments)
}, 时间)
}
}
const 函数名 = (参数) => {
console.log(参数)
}
const 初始化 = 防抖(函数名, 时间)
初始化()