记录部分常用函数的实现(3):防抖 节流

一、防抖
function debounce (func, wait, immediate) {
    let timeout, result

    let debounced = function () {
        let context = this
        let args = arguments

        clearTimeout(timeout)
        if(immediate) {
            let callNow = !timeout  // 触发执行一次过后等不触发的wait后触发才能执行
            timeout = setTimeout(function () {
                timeout = null
            }, wait)
            if(callNow) result = func.apply(context, args)
        } else {
            timeout = setTimeout(function () {
                func.apply(context, args)
            }, wait)
        }

        return result
    }

    debounced.cancel = function () {
        clearTimeout(timeout)
        timeout = null
    }

    return debounced
}
二、节流
function throttle (func, wait, options) {
        let timeout, context, args, result
        let previous = 0
        if(!options) options = {}

        let later = function () {
            previous = options.leading === false ? 0 : +new Date()
            timeout = null
            func.apply(context, args)
            if(!timeout) context = args = null
        }

        // 假设leading和trailing都为false,则鼠标第一次移进后移出再移进,此时的previous不是0,因此只要第二次移入的时间是wait之后,则就会马上触发,就违背了leading == false
        // 可以给mouseout绑定让previous = 0但不清除定时器
        let throttled = function () {
            let now = +new Date()
            if(!previous && options.leading === false) previous = now
            context = this
            args = arguments
            let remaining = wait - (now - previous)
            
            if(remaining <= 0 || remaining > wait) {
                if(timeout) {
                    clearTimeout(timeout)
                    timeout = null
                }
                previous = now
                func.apply(context, args)
                if(!timeout) context = args = null
            } else if (!timeout && options.trailing !== false) {
                timeout = setTimeout(later, remaining)
            }

        }

        throttled.cancel = function () {
            clearTimeout(timeout)
            previous = 0
            timeout = null
        }

        return throttled
    }

参考:https://github.com/mqyqingfeng/Blog/issues/26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值