实现简易版的防抖和节流

//防抖
//核心思想:
//在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#
全部评论
佩服啊,太牛啦
点赞 回复 分享
发布于 2022-10-20 13:07 山西
请问为什么要用到apply
点赞 回复 分享
发布于 2022-10-24 15:29 广东

相关推荐

01-18 09:26
已编辑
门头沟学院 Java
王桑的大offer:建议中间件那块写熟悉即可,写掌握 面试包被拷打到昏厥
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客企业服务