2022-05-26 04:45:45 +00:00
|
|
|
export function throttle(func, wait, options?: { leading: boolean; trailing: boolean }) {
|
|
|
|
let context, args, result;
|
|
|
|
let timeout = null;
|
|
|
|
let previous = 0;
|
|
|
|
|
2022-06-03 10:47:34 +00:00
|
|
|
if (!options) options = { leading: false, trailing: true };
|
2022-05-26 04:45:45 +00:00
|
|
|
|
|
|
|
const later = function () {
|
|
|
|
previous = options.leading === false ? 0 : Date.now();
|
|
|
|
timeout = null;
|
|
|
|
result = func.apply(context, args);
|
|
|
|
if (!timeout) context = args = null;
|
|
|
|
};
|
|
|
|
|
|
|
|
return function () {
|
|
|
|
const now = Date.now();
|
|
|
|
if (!previous && options.leading === false) previous = now;
|
|
|
|
const remaining = wait - (now - previous);
|
|
|
|
context = this;
|
|
|
|
// eslint-disable-next-line prefer-rest-params
|
|
|
|
args = arguments;
|
|
|
|
if (remaining <= 0 || remaining > wait) {
|
|
|
|
if (timeout) {
|
|
|
|
clearTimeout(timeout);
|
|
|
|
timeout = null;
|
|
|
|
}
|
|
|
|
previous = now;
|
|
|
|
result = func.apply(context, args);
|
|
|
|
if (!timeout) context = args = null;
|
|
|
|
} else if (!timeout && options.trailing !== false) {
|
|
|
|
timeout = setTimeout(later, remaining);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
};
|
|
|
|
}
|