const debounce = (func, wait, immediate = false) => {
let timeout = null;
let shouldInvoke = immediate;
return function (...args) {
const context = this;
if (shouldInvoke) {
func.apply(context, args);
shouldInvoke = false;
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
if (!immediate) func.apply(context, args);
shouldInvoke = immediate;
}, wait);
};
};
const throttle = (fn, time, immediately = true, last = false) => {
let imm = immediately;
let flag = immediately;
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
const _this = this;
if (flag) {
fn.apply(_this, arguments);
flag = false;
setTimeout(() => {
flag = true;
}, time);
} else {
if (!imm) {
imm = true;
setTimeout(() => {
flag = true;
}, time);
}
if (last) {
timer = setTimeout(() => {
fn.apply(_this, arguments);
}, time);
}
}
};
};