1 介绍
函数防抖和函数节流一般是用来解决持续触发事件的问题。例如处理以下事件时:mouseover、scroll和resize。实现防抖和节流的本质是利用计时器计算事件持续触发的时间。
(1)函数防抖(debounce)
持续触发事件后n秒内函数只会执行一次,如果n秒内事件再次触发,清空计时器重新计时。
(2)函数节流J(throttle)
持续触发事件后 n 秒内函数只执行一次。
2 截图
3 Vue源码
<template>
<div class="test">
<div class="item" v-on:mousemove="changeNum">
<div>数据变化</div>
<div>{{ num }}</div>
</div>
<div class="item" v-on:mousemove="debounce">
<div>防抖</div>
<div>{{ debounceNum }}</div>
</div>
<div class="item" v-on:mousemove="throttle">
<div>节流</div>
<div>{{ throttleNum }}</div>
</div>
</div>
</template>
<script>
export default {
name: "Test",
data: function () {
return {
num: 1,
debounceNum: 1,
throttleNum: 1,
debounceTimeout: null,
throttleTimeout: null,
};
},
methods: {
changeNum: function () {
this.num = this.num + 1;
},
// 防抖
debounce: function (evt, delay = 1000) {
// 清空计时器
if (this.debounceTimeout != null) {
clearTimeout(this.debounceTimeout);
}
// 计时
this.debounceTimeout = setTimeout(() => {
this.debounceNum = this.debounceNum + 1;
}, delay);
},
// 节流
throttle: function (evt, delay = 1000) {
// 判断计时是否结束
if (this.throttleTimeout != null) {
return;
}
// 计时
this.throttleTimeout = setTimeout(() => {
this.throttleNum = this.throttleNum + 1;
clearTimeout(this.throttleTimeout);
this.throttleTimeout = null;
}, delay);
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.test {
width: 100%;
font-size: 30px;
}
.item {
width: 100%;
height: 90px;
background-color: #cccccc;
margin: 40px;
}
</style>