节流和防抖的区别
- 防抖(Debounce):
- 触发高频事件后,n秒内函数只会执行一次,如果在n秒内又触发了该事件,则会重新计算函数执行时间。即延迟执行,每次触发事件都会取消之前的延迟调用,重新开始计时。
- 例如搜索框输入,用户输入过程中不会立刻发起搜索,而是在用户停止输入一段时间后才发起搜索请求,这样可以避免用户每次输入都发起请求。
- 节流(Throttle):
- 规定在一个单位时间内,只能触发一次函数。无论在这个时间内触发了多少次事件,都只会在规定时间间隔内执行一次函数。
- 比如滚动条滚动事件,为了避免频繁触发计算,可以设置每100ms执行一次相关函数,而不是每次滚动都执行。
使用防抖处理按钮点击事件的代码
<template>
<div>
<button @click="debounceClick">点击按钮</button>
</div>
</template>
<script>
export default {
methods: {
debounce(func, wait) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
},
apiCall() {
console.log('发起接口请求');
},
debounceClick: null
},
created() {
this.debounceClick = this.debounce(this.apiCall, 300);
}
};
</script>
使用节流处理按钮点击事件的代码
<template>
<div>
<button @click="throttleClick">点击按钮</button>
</div>
</template>
<script>
export default {
methods: {
throttle(func, wait) {
let previous = 0;
return function() {
const context = this;
const args = arguments;
const now = new Date().getTime();
if (now - previous >= wait) {
func.apply(context, args);
previous = now;
}
};
},
apiCall() {
console.log('发起接口请求');
},
throttleClick: null
},
created() {
this.throttleClick = this.throttle(this.apiCall, 300);
}
};
</script>
选择场景
- 防抖适用场景:
- 搜索框联想:用户输入过程中不需要频繁请求联想数据,在用户停止输入后发起请求获取联想结果,减少不必要的请求。
- 表单提交:防止用户多次点击提交按钮,在用户点击后延迟一段时间,如果用户没有再次点击则提交表单,避免重复提交。
- 节流适用场景:
- 滚动加载:在滚动条滚动过程中,设置每隔一段时间加载一次新的数据,避免滚动过程中频繁请求加载数据。
- 鼠标连续点击:例如点赞按钮,防止用户快速多次点击,设置每间隔一定时间才允许点击生效一次。