防抖函数&节流函数

防抖函数

能够控制某个方法的执行次数。如果一个方法在一定时间内的执行次数过多而我们并不需要这个方法执行很多次,我们就可以使用防抖函数来减少函数的执行次数

//防抖函数
const debounce = function (func, delay, immediately = false) {
    let timer = null
    if (immediately) {  //立即执行操作
        return function (...args) {
            if (timer) clearTimeout(timer);
            let callNow = !timer;
            timer = setTimeout(() => {
                timer = null
            }, delay)
            if (callNow) func.apply(this, args)
        }
    } else {  //delay时间后执行操作
        return function (...args) {
            if (timer) clearTimeout(timer)
            timer = setTimeout(() => {
                func.apply(this, args)
            }, delay)
        }
    }
}
节流函数

节流函数的作用是在某一段时间内函数只执行一次,它能控制函数的执行频率

//节流函数
const throttle = function (func, delay) {
    let timer = null
    return function (...args) {
        if (!timer) {
            timer = setTimeout(() => {
                timer = null
                func.apply(this, args)
            }, delay)
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值