实现简易版的防抖和节流
//防抖
//核心思想:
//在delay时间间隔内,当事件再次触发时,移除之前的定时器,重新设置定时器
function myDebounce(execFn, delay) {
let timer = 0
function _debounce(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
execFn.apply(this, args)
timer = null
}, delay)
}
return _debounce
}
//节流
//核心思想:
//计算当前时间与初始时间的时间差,然后用间隔时间与其作差,得到等待时间,等待时间 <= 0时execFn执行。
function myThrottle(execFn, interval) {
const initTime = 0
function _throttle(...args) {
let nowTime = Date.now()
const waitTime = interval - (nowTime - initTime)
if (waitTime <= 0)
execFn.apply(this, args)
initTime = nowTime
}
return _throttle
} #js#

联想公司福利 1502人发布