项目场景:
今天在做列表的全选功能用的el-table,点击全选后面的几页也勾选上,导致了一个问题,我在selection-change回调函数中,请求的接口被反复调用,因为全选会勾选第一页每一条记录,都会触发,所以用到了防抖功能
代码片段(防抖函数)
1.这是我封装到了debounce.js文件中的防抖函数:
// 防抖函数
export function debounce(func, delay) {
let timer = null;
return function(...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
}
}
2.防抖函数项目中的运用
import {debounce} from '../../utils/debounce.js'
handleChange(){
debounce(() => {
this.$store.dispatch("yangben/previewPoint", { ids: this.selectLabelAll, type: this.type });
}, 300)
}
节流函数补充:
1.节流函数代码
// 节流
export const throttle=(fn, delay) => {
// 时间戳
var timeTwo = 0 //new Date();
// 定时器
var timeThree = null;
return function() {
let context = this;
let args = arguments;
var now = new Date()
// !!!!时间戳实现【new Date()虽然获取结果不是时间戳但是计算结果会自动转化为时间戳】
// if(now-timeTwo>=delay){
// fn.apply(context,args);
// timeTwo=new Date();
// }
// !!!!定时器实现
// if (!timeThree) {
// timeThree = setTimeout(function () {
// fn.apply(context, args);
// timeThree=null;
// }, delay)
// }
// 结合 ps:最后一次触发在固定频率内会在延迟后触发
var wait = delay - (now - timeTwo)
clearTimeout(timeThree)
if (wait <= 0) {
fn.apply(context, args);
timeTwo = new Date();
} else {
timeThree = setTimeout(function() {
fn.apply(context, args);
}, delay)
}
}
}
2.节流函数代码调用
//节流
throttling: throttle(function (...args) {
this.throttlingBtn(...args)
}, 1000),
总结
防抖:
1.函数执行之后,在规定时间内如果再次触发,会清空clearTimer(),重新开始计时。前面的触发都会取消,最后一次执行 在 规定的时间 之后才会触发。如果连续快速触发,只执行最后一次
2.应用场景:输入框输入
节流:
1.在规定时间内,只触发一次,个人理解就是有个时间段,在这个时间段执行一次
2.应用场景:文件下载(避免多次点击,下载很多个)
大家可以参考另一位博主文章: vue2项目中按钮实现防抖、节流功能,包含封装代码以及使用