实现简易版的防抖和节流

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

相关推荐

仁者伍敌:服务员还要脱颖而出,这是五星级酒店吗
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务