闭包是个老生长谈的问题,本文不说什么是闭包,说说闭包在实际中的应用,我们可以使用闭包来实现函数节流和函数防抖
函数节流
const throttle = (fn, wait) => {
let preTime = Date.now()
return function() {
if(Date.now() - pre > wait) {
fn()
preTime = Date.now()
}
}
}
函数防抖
const debounce = (fn,wait) => {
let timer = null
return function() {
if(timer) {
clearTimeout(timer)
}
timer = setTimeout(fn, wait)
}
}
小结
这里简单的介绍了通过闭包实现了函数节流和函数防抖,核心是throttle
函数中的preTime
和debounce
的函数中的timer
变量来判断实现函数节流和防抖。