防抖函数的原理:
只有在事件触发的时候才会延迟加载,如果在延迟加载之前再次触发,则会刷新延迟时间重新延迟,触发次数有且只有触发一次;
使用场景:
防抖函数一般是用于频繁触发事件,而我们只需要它触发一次的场景,比如:输入框的oninput事件、button按钮点击事件、点赞等操作场景;
实例:
例如在vue-cli脚手架中使用防抖函数来进行提升性能
vue-cli:
定义一个util.js
// 函数防抖
export function debounce(fn, wait) {
let timeout = null;
wait = wait || 600;
return function () {
let that = this;
if(timeout !== null) clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(that);
}, wait);
}
}
(注意:我们在vue-cli中自定义方法必须要export抛出,不然组件读取不到)
使用和引用组件:
import {debounce} from "@/utils/utils"
调用方法:
methods: {
inputNum: debounce(function(){
console.log(1111);
}, 1000)
}
后记:
// eg1 : 防抖函数
valueChange() {
debounce(function () {
console.log("测试");
return function(){}
}, 1000);
},
eg2:
valueChange: debounce(function () {
console.log("测试");
return function(){}
}, 1000),
注意两种函数的写法,
第一种,当valueChange执行, 触发debounce函数,并把return的函数返回到debounce上。
第二种: valueChange 是一个变量,等于debounce 返回什么值,返回的内容返回给valueChange .
vue中使用:
util.js
// 函数防抖
export default {
debounce(fn, wait) {
let timeout = null;
wait = wait || 600;
return function () {
let that = this;
console.log(this)
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(that);
}, wait);
}
}
}
vue页面 使用
// 防抖函数
valueChange: utils.debounce(function () {
this.inputChange();
}, 500),