学习笔记十防抖节流

防抖与节流

1. 防抖就是用户多次触发事件 但是只执行最后的一次
2. 设置debounce函数 返回一个函数 利用闭包的思想 在外层函数设置定时器id 内层函数设置定时器 在最开始清除定时器 然后一定时间间隔执行事件 return的函数的this和event是要执行函数的 所以在外面设置变量 交给定时器内部的函调函数 改变event和this
        let btn = document.getElementById('btn');
    function debounce(fun, delay) {
        let timer;
    return function () {
        let args=arguments;
        clearTimeout(timer);
        timer=setTimeout(()=>{
            fun.apply(this, args);
        },delay)
    }
    }
    btn.onclick = debounce(function (e) {
        console.log(this, e);
    }, 300)
4. 节流是多次触发 减少执行的次数

设置throttle函数 先设置一个开始的时间戳为0 return一个函数 里面设置现在的时间戳为now 相差大于delay才执行,执行完设置开始时间戳为now

        function throttle(fun, delay) {
        let before = 0;
        return function () {
            let context = this;
            let args = arguments;
            let now = new Date().valueOf();
            if (now - before > delay) {
                fun.apply(context, args);
                before = now;
            }
        }
    }

另一种方法:设置timer=true 在定时器回调里设置timer=true 在外面设置timer=false

        function throttle(fun, delay) {
        timer = true;
        return function () {
            let context = this;
            let args = arguments;
            if (timer) {
                timer = setTimeout(() => {
                    fun.apply(context, args);
                    timer = true;
                }, delay)
            }
            timer=false;

        }
    }
    ```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值