防抖与节流

防抖

定义:

n 秒后再执行该事件,若在 n 秒内被重复触发,则重新计时

应用场景:

  • 按钮点击太快重复提交

  • 调整浏览器窗口,resize次数过于频繁,造成计算过多

  • 手机号、邮箱验证输入检测等

debounce(callback, delay) {
    let timer;
    return function() {
        let that = this;
        let args = arguments;
        if(timer) { 
            clearTimeout(timer)
        }
        timer = setTimeout(function(){
            callback.apply(that, args)
        }, delay);      
    }
}

eg:

<template>
    <div>
        <input type="text" @keyup="debounce" />
    </div>
</template>
 
<script>
export default {
    data() {
        return {
            timer: null
        }
    },
    methods: {
        debounce() {
            if(this.timer) {
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
                console.log("防抖...")
                this.timer = null
            }, 2000)
        }
    }
}
</script>

节流

定义:

在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效。

应用场景:

  • 滚动加载,加载更多或滚到底部监听

  • 搜索框,搜索联想功能

thorttle(callback, delay) {
    let timer;
    return function () {
        let that = this;
        let args = arguments;
        if(!timer) {
            timer = setTimeout(function(){
                timer = null;
                callback.apply(that, args)
            }, delay)
        }
    }
} 

eg:

<template>
    <div>
        <button @click="throttle">按钮</button>
    </div>
</template>
 
<script>
export default {
    data() {
        return {
            timer: null,
            lastTime: null
        }
    },
    methods: {
        throttle() {
            let now = +new Date()
            if(this.lastTime && now - this.lastTime < 200) {
                clearTimeout(this.timer)
            } else {
                this.lastTime = now
                this.timer = setTimeout(() => {
                    console.log("节流...")
                    this.lastTime = +new Date()
                }, 1000)
            }
        }
    }
}
</script>

防抖 VS 节流

相同:

  • 都可以通过使用 setTimeout 实现

  • 目的都是,降低回调执行频率。节省计算资源

不同:

  • 防抖,在一段连续操作结束后,处理回调,利用clearTimeout和 setTimeout实现。

  • 防抖,关注一定时间连续触发的事件,只在最后执行一次,

  • 节流,一段时间内只执行一次

  • 节流,在一段连续操作中,每一段时间只执行一次,频率较高的事件中使用来提高性能

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

笨笨翔!

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

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

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

打赏作者

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

抵扣说明:

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

余额充值