防抖
普通防抖
functiondebounce(fn, delay=200) {
// 记录上⼀次的延时器
vartimer=null;
returnfunction (...args) {
// 清除上⼀次延时器
timer&&clearTimeout(timer);
timer=setTimeout(() => {
fn.apply(this, args);
}, delay);
}
}
自执行函数版
constdebounce= (() => {
lettimer=null;
return (fn, delay=200) => {
timer&&clearTimeout(timer);
timer=setTimeout(fn, delay);
}
})()
vue3版
functiondebounce(fn, delay=300) {
// 记录上⼀次的延时器
vartimer=null;
return (function (...args) {
timer&&clearTimeout(timer);
timer=setTimeout(() => {
fn.apply(this, args);
}, delay);
})();
}
使用防抖
methods: {
loadList() {
debounce(() => {
console.log('加载数据')
}, 500)
}
}
节流
定时器版
functionthrottle(fn, delay=300){
lettimer=null;
returnfunction(...args) {
if (!timer) {
timer=setTimeout(() => {
fn.apply(this, args);
clearTimeout(timer);
timer=null;
}, delay)
}
}
}
functionthrottle(fn, delay=300) {
letisThrottling=false
// 核心思路,函数多次执行只有当 isThrottling 为 false 时才会进入函数体
returnfunction (...args) {
if (!isThrottling) {
isThrottling=true;
setTimeout(() => {
isThrottling=false;
fn.apply(this, args);
}, delay)
}
}
}
时间戳版
functionthrottle(fn, delay=200){
varlastTime=Date.now();
returnfunction (...args) {
varnowTime=Date.now();
if (nowTime-lastTime>delay) {
lastTime=nowTime;
fn.apply(this, args);
}
}
}
vue3版
functionthrottle(fn, delay=300) {
varlastTime=Date.now();
return (function (...args) {
varnowTime=Date.now();
if (nowTime-lastTime>delay) {
lastTime=nowTime;
fn.apply(this, args);
}
})();
}
使用节流
methods:{
appSearch:debounce(function(){
this.getList()
},300)
}