函数防抖和函数节流

函数防抖

应用场景一:浏览器窗口尺寸发生改变

        let handle = debounce(function (width) {
            console.log(width)
        }, 1000)

        window.onresize = function () {
            handle(document.documentElement.clientWidth)
        }

应用场景二:input元素的值不断改变时

    <input type="text" name="" id="">
  
        let int = document.querySelector("input")
        let bundle = debounce(function (value, that) {
            console.log(value)
            console.log(that)
        }, 1000)
        int.oninput = function () {
            bundle(this.value, this)
        }

函数防抖代码实现

function debounce(callback, delay) {
    let timer = null
    return function (..args) {
            clearTimeout(timer)
        timer = setTimeout(function => {
            callback.apply(null, args)
        }, delay)
    }
}

函数节流

 应用场景一:浏览器窗口尺寸发生改变

        let handle = debounce(function (width) {
            console.log(width)
        }, 1000)

        window.onresize = function () {
            handle(document.documentElement.clientWidth)
        }

应用场景二:input元素的值不断改变时

    <input type="text" name="" id="">
  
        let int = document.querySelector("input")
        let bundle = debounce(function (value, that) {
            console.log(value)
            console.log(that)
        }, 1000)
        int.oninput = function () {
            bundle(this.value, this)
        }

函数节流代码实现

有两种情况:

1.立即执行,使用时间戳
2.延迟执行,和防抖的实现大同小异
function debounce(callback, delay, immediately) {

    if (immediately) {
        let time
        return function () {
            if (!time || Date.now() - time >= delay) {
                callback.apply(null, arguments)
                time = Date.now()
            }
        }
    }
    else {
        let timer
        return function (...args) {
            if (timer) {
                return
            }
            timer = setTimeout(function => {
                callback.apply(null, args)
                //没有显式取消定时器(定时器仍会在后台触发)
                //只是移除了对定时器ID的引用
                timer = null
            }, delay)
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值