33 lines
940 B
TypeScript
33 lines
940 B
TypeScript
|
|
/**
|
||
|
|
* Throttle function execution to a maximum frequency.
|
||
|
|
*
|
||
|
|
* @param fn Function to throttle.
|
||
|
|
* @param wait Maximum time between function calls.
|
||
|
|
* @returns Throttled function.
|
||
|
|
*/
|
||
|
|
export function throttle<T extends (...args: any[]) => any>(
|
||
|
|
fn: T,
|
||
|
|
wait: number,
|
||
|
|
): (...args: Parameters<T>) => void {
|
||
|
|
let lastCall = 0;
|
||
|
|
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||
|
|
|
||
|
|
return (...args: Parameters<T>) => {
|
||
|
|
const now = Date.now();
|
||
|
|
const timeSinceLastCall = now - lastCall;
|
||
|
|
|
||
|
|
if (timeSinceLastCall >= wait) {
|
||
|
|
lastCall = now;
|
||
|
|
fn(...args);
|
||
|
|
} else {
|
||
|
|
// Schedule for end of wait period
|
||
|
|
if (timeoutId) clearTimeout(timeoutId);
|
||
|
|
timeoutId = setTimeout(() => {
|
||
|
|
lastCall = Date.now();
|
||
|
|
fn(...args);
|
||
|
|
timeoutId = null;
|
||
|
|
}, wait - timeSinceLastCall);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
}
|