节流
function throttle(callback, wait = 300) {
let start = 0;
return function (...args) {
let now = Date.now();
if (now - start >= wait) {
callback.call(this, ...args);
start = now;
}
};
}
防抖
function debounce(callback, time = 300) {
let timeId = null;
return function (...args) {
if (timeId !== null) {
// 清空定时器
clearTimeout(timeId);
}
timeId = setTimeout(() => {
callback.call(this, ...args);
timeId = null;
}, time);
};
}
使用
// VUE
submitEvent: throttle(function (ev) {
this.$emit("submit-event", ev);
}, 700),
el.addEventListener('click',throttle(fn))