防抖 节流 应用

防抖函数

概念

所谓防抖,就是指触发事件 N 秒后才执行函数,如果在 N 秒内又触发了事件,则会重新计算函数执行时间,也就是说,最后一次触发事件后的N秒后执行函数

实现

<button class="debounceButton">防抖事件</button>

<script>
    // 获取防抖事件按钮
    const debounceButton = document.querySelector('.debounceButton');
    // 分装防抖函数
    function debounce (debounceCb, delay = 1000) {
        let timer;
        return (...args) => {
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                debounceCb.apply(this.args)
            }, delay)
        }
    };
    // 调用防抖函数
    debounceButton.addEventListener('click', debounce(e => {
        console.log('防抖事件');
    }))
</script>

节流函数

概念

所谓节流,就是指连续触发事件但是在 N 秒中只执行一次函数,也就是说,在触发事件后,不管你触发了多少次,它都是在每 N 秒执行一次

实现

<button class="throttleButton">节流事件</button>
<srcipt>
    // 获取节流事件按钮
    const throttleButton = document.querySelector('.throttleButton');
    // 封装节流函数
    function debounce (debounceCb, delay = 1000) {
        let timer;
        return (...args) => {
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                debounceCb.apply(this.args)
            }, delay)
        }
    };
    // 调用节流函数
    throttleButton.addEventListener('click', throttle(e => {
        console.log('节流事件')
    }))
</srcipt>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

热乎劲的小仓库

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值