/* 多次点击 只执行最后一次 */
const debounce = (function () {
let timer = null;
return function (func, delay = 1000) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(func, delay);
};
})();
/* 先执行一次 */
const debounce2 = (function () {
let timer = null;
let flag = true;
return function (func, delay = 1000) {
if (flag) {
flag = false;
func.call();
return;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
flag = true;
func.call();
}, delay);
};
})();
export default {
debounce,
debounce2,
};
/* 挂载到原型 */
import debounce from "./debounce/debounce";
Vue.prototype.$utils = {
...debounce,
};
/* 使用 */
this.$utils.debounce(() => {
// ...
}, 500);