js 函数节流

一。函数防抖:基本思想是指,某些代码不可以在没有间断的情况连续重复执行。第一次调用函数, 创建一个定时器,在指定的时间间隔之后运行代码。当第二次调用该函数时,它会清除前一次的定时器 并设置另一个。如果前一个定时器已经执行过了,这个操作就没有任何意义。然而,如果前一个定时器 尚未执行,其实就是将其替换为一个新的定时器。目的是只有在执行函数的请求停止了一段时间之后才 执行。常用于 onresize 事件

function debounce (fn, delay = 100, context) {
        let Timer = 0
        return function () {
            clearTimeout(Timer)
            Timer = setTimeout(() => {
                fn.call(context)
            }, delay)
        }
    }

测试代码:

 function test () {
        console.log('我是测试代码!')
    }

    let variable = debounce(test)
    for (let i = 0; i < 10000; i++) {
        variable()
    }
输出:我是测试代码!

最终发现通过调用10000次改函数结果只触发了一次。并且触发的时间是执行完后延迟 100ms才输出的。首次不会触发

二。函数节流:指在指定的时间内,只触发一次。

function throttle (fn, delay = 100, context) {
        let last = 0
        return function () {
            let now = new Date().valueOf()
            if (now - last > delay || !last) {
                last = now
                fn.call(context)
            }
        }
    }
 function test () {
        console.log('我是测试代码!')
    }

    let variable = throttle(test)
    for (let i = 0; i < 10000; i++) {
        variable()
    }
输出:我是测试代码!

先立即输出。缺陷最后一次的操作并不能保证一定触发。

三。组合模式。

function compose (fn, delay = 100, context) {
        let Timer = 0,
            last = 0
        return function () {
            let now = new Date().valueOf()
            if (now - last > delay || !last) {
                last = now
                fn.call(context)
            }
            clearTimeout(Timer)
            Timer = setTimeout(() => {
                fn.call(context)
            }, delay)
        }
    }

首次和最后一次的操作都会触发。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值