mirror of
https://github.com/block/buzz.git
synced 2026-08-18 06:50:31 +02:00
Signed-off-by: Wes <wesbillman@users.noreply.github.com> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co>
41 lines
1.0 KiB
TypeScript
41 lines
1.0 KiB
TypeScript
export type TrailingDebounce = {
|
|
/** Schedule the action, restarting the quiet window on every call. */
|
|
trigger: () => void;
|
|
/** Cancel any pending action (e.g. on unmount). */
|
|
cancel: () => void;
|
|
};
|
|
|
|
type TimerHost = {
|
|
setTimeout: (handler: () => void, ms: number) => number;
|
|
clearTimeout: (id: number) => void;
|
|
};
|
|
|
|
/**
|
|
* Trailing debounce: a burst of `trigger()` calls collapses into a single
|
|
* `action()` that runs once, `delayMs` after the last call. The timer is
|
|
* restarted on every trigger, so a sustained burst keeps deferring until quiet.
|
|
*/
|
|
export function createTrailingDebounce(
|
|
action: () => void,
|
|
delayMs: number,
|
|
host: TimerHost = window,
|
|
): TrailingDebounce {
|
|
let timeoutId: number | undefined;
|
|
const cancel = () => {
|
|
if (timeoutId !== undefined) {
|
|
host.clearTimeout(timeoutId);
|
|
timeoutId = undefined;
|
|
}
|
|
};
|
|
return {
|
|
trigger: () => {
|
|
cancel();
|
|
timeoutId = host.setTimeout(() => {
|
|
timeoutId = undefined;
|
|
action();
|
|
}, delayMs);
|
|
},
|
|
cancel,
|
|
};
|
|
}
|