防抖节流的区别以及用法

防抖(多次触发 只执行最后一次)

防抖策略(debounce)是当事件被触发后,延迟n秒后再执行回调,如果在这n秒内事件又被触发,则重新计时。

Vue写法:

<template>
	<a-input @change="handleChange"></a-input>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
    data() {
        return {
            // 定时器
            timer: null,
        }
    },
	methods: {
		handleChange() {
    		if (this.timer) {
          		clearTimeout(this.timer);
        	}
        	this.timer = setTimeout(() => {
          		// 业务逻辑
    			console.log('=============');
        	}, 200);
		}
    },
})
</script>

JavaScript写法:

let timer = null;
if (this.timer) {
	clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
	// 业务逻辑
	console.log('=============');
}, 200);

节流(规定时间内 只触发一次)

节流策略(throttle),控制事件发生的频率,如控制为1s发生一次,甚至1分钟发生一次。

Vue写法:

<template>
	<a-input @change="handleChange"></a-input>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
    data() {
        return {
            //开始时间
            firstTime: 0,
        }
    },
	methods: {
		handleChange() {
    		/* 获取当中时间的事件戳 */
          	let nowTime = new Date();
          	if (nowTime - this.firstTime < 1000) {
            	//不要让代码往后面走,就是不要触发事件
            	return;
          	}
          	//下一个时间段,又是从头开始
          	this.firstTime = nowTime;
    
    		// 业务逻辑
    		console.log('=============');
		}
    },
})
</script>

JavaScript写法:

let firstTime = 0;
let nowTime = new Date();
if (nowTime - this.firstTime < 1000) {
    return;
}
this.firstTime = nowTime;
// 业务逻辑
console.log('=============');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值