File size: 807 Bytes
2409829 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
export type Debouncer = ReturnType<typeof debouncer>;
export type DebouncerOptions = {
debounceTime: number;
};
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function debouncer<T>(callFn: (value: T) => unknown, { debounceTime = 60 }: Partial<DebouncerOptions> = {}) {
let currentValue: T | undefined;
let recentlyUpdated: boolean = false;
const debounceEmitValue = () => {
recentlyUpdated = false;
if (currentValue === undefined) return;
debounceUpdateValue(currentValue);
};
const debounceUpdateValue = (newValue: T) => {
if (recentlyUpdated) {
currentValue = newValue;
return;
}
callFn(newValue);
recentlyUpdated = true;
currentValue = undefined;
setTimeout(debounceEmitValue, debounceTime);
};
return { debounceUpdateValue };
}
|