import type { Awaited } from '../../types'; type Func = (...args: any[]) => any; export type DebouncedFunction = ( this: ThisParameterType, ...args: Parameters ) => Promise>>; // Debounce a function call to the trailing edge. // The debounced function returns a promise. export function debounce( func: TFunction, wait: number ): DebouncedFunction { let lastTimeout: ReturnType | null = null; return function (...args) { return new Promise((resolve, reject) => { if (lastTimeout) { clearTimeout(lastTimeout); } lastTimeout = setTimeout(() => { lastTimeout = null; Promise.resolve(func(...args)) .then(resolve) .catch(reject); }, wait); }); }; }