防抖方法。
//防抖方法
const debounce = (fn, delay) => {
let timer;
return function (...args) {
if (timer) {
console.log("clear")
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};
const task = () => {
console.log("run task");
};
const debounceTask = debounce(task, 1000);
<button @click="debounceTask">防抖</button>
节流方法。
//节流方法
const throttle = (fn, delay) => {
let last = 0; // 上次触发时间
return function (...args) {
const now = Date.now();
if (now - last > delay) {
last = now;
fn.apply(this, args);
}
};
};
const task = () => {
console.log("run task");
};
const throttleTask = throttle(task, 1000); //节流
<button @click="throttleTask">节流</button>