m3-academy-template-vtexio-.../custom/react/utils/throttle.ts

27 lines
837 B
TypeScript
Raw Normal View History

2022-08-11 13:06:07 +00:00
export const throttle = <F extends (...args: any[]) => any>(
func: F,
waitFor: number
): any => {
const now = () => new Date().getTime();
const resetStartTime = () => (startTime = now());
let timeout: any;
let startTime: number = now() - waitFor;
return (...args: Parameters<F>): Promise<ReturnType<F>> =>
new Promise((resolve) => {
const timeLeft = startTime + waitFor - now();
if (timeout) {
clearTimeout(timeout);
}
if (startTime + waitFor <= now()) {
resetStartTime();
resolve(func(...args));
} else {
timeout = setTimeout(() => {
resetStartTime();
resolve(func(...args));
}, timeLeft);
}
});
};