防抖和节流实现
防抖(debounce)
debounce(fn, wait) {
let timer = null
return function() {
timer && clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, wait)
}
}
节流(throttle)
throttle(fn, time) {
let oldTime = Date.now()
return function() {
let nowTime = Date.now()
if(nowTime - oldTime > time) {
fn.apply(this, arguments)
oldTime = nowTime
}
}
}
实战运用
行百里者半九十