浅析Vue 防抖与节流的使用

2020-06-12 21:03:57易采站长站整理

if (lastTime && lastTime - now < 200) { //在200ms内点击多次,只有一次生效
clearTimeout(timer);
}
timer = setTimeout(() => {
console.log("点击...");
lastTime = +new Date();
}, 200);
}
}
};
</script>

效果演示:

 

补充

当然,也可以对这两个方法进行封装,以便在多处使用。


/**
* 函数防抖 (只执行最后一次点击)
*/
export const Debounce = (fn, t) => {
let delay = t || 500;
let timer;
console.log(fn)
console.log(typeof fn)
return function () {
let args = arguments;
if(timer){
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
}
};
/*
* 函数节流
*/
export const Throttle = (fn, t) => {
let last;
let timer;
let interval = t || 500;
return function () {
let args = arguments;
let now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(this, args);
}, interval);
} else {
last = now;
fn.apply(this, args);
}
}
};

总结

以上所述是小编给大家介绍的Vue 防抖与节流的使用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对软件开发网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!