一、防抖和节流的概念和使用场景
防抖(debounce):防止重复触发事件,用户在短时间内频繁触发事件时,定时器会不断清空,直到指定时间后才执行回调函数,所以用户在频繁触发事件过程中,只会执行一次回调函数。
使用场景:频繁触发事件,搜索框输入值,监听浏览器窗口resize,表单提交按钮,登录发短信等等
-------------------------------------------------------------------------------------------------------------------------------
节流(throttle):节流和防抖有点类似,节流是在规定的时间里,只执行一次,节流可以减少不断执行频率,和游戏的技能冷却时间类似。
使用场景:频繁触发事件,onscroll滚动,mousemove 等等
二、参考流程图
三、核心代码实现
防抖实现代码:
function debounce(func, wait) {
//防抖
let timer;
// 在后续触发事件时,是直接触发的回调函数,不会去重新定义 timer
return function() {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, arguments);
}, wait);
};
}
节流实现代码:
function throttle(func, wait) {
//节流
let timer = null;
//以后每次事件触发只会调用回调函数
return function() {
if (timer) { //如果timer一旦赋值了就等待
return;
} else {
timer = setTimeout(() => {
func.apply(this, arguments);
timer = null; //函数执行完毕清空timer
}, wait);
}
}
}
使用防抖或节流的index.vue
<template>
<div>
<div class="contain" @mousemove="count">{{ num }}</div>
</div>
</template>
<script>
import { debounce, throttle } from "@/assets/js/util.js";
export default {
data() {
return {
num: 0
}
},
methods: {
count: throttle(function () {
this.num++
}, 2000),
}
}
</script>
<style>
.contain {
width: 100%;
height: 100px;
background: pink;
font-size: 28px;
line-height: 100px;
color: white;
}
</style>
封装方法到util.js
function debounce(func, wait) {
//防抖
let timer;
// 在后续触发事件时,是直接触发的回调函数,不会去重新定义 timer
return function() {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, arguments);
}, wait);
};
}
function throttle(func, wait) {
//节流
let timer = null;
return function() {
if (timer) {
return;
} else {
timer = setTimeout(() => {
func.apply(this, arguments);
timer = null;
}, wait);
}
};
}
export { debounce, throttle };