Files
Graphite/frontend/src/utility-functions/debounce.ts
Keavon Chambers 34c6c0431b Improve NumberInput with dragging to change value and escape/right-click to abort (#1469)
* Improve NumberInput with dragging to change value and escape to abort

Closes #1468

* Fix slowing with Shift and integer mode
2023-11-21 17:26:28 -08:00

32 lines
807 B
TypeScript

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 };
}