diff --git a/src/index.ts b/src/index.ts index 8fbedae..5063c38 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,34 +1,37 @@ -/** - * A function that emits a side effect. - */ -export type Procedure = (...args: any[]) => any; - -export type Options = { +export type Options = { isImmediate?: boolean; maxWait?: number; - callback?: (data: TT) => void; + callback?: (data: Result) => void; }; -export interface DebouncedFunction { - (this: ThisParameterType, ...args: Parameters): Promise>; +export interface DebouncedFunction< + Args extends unknown[], + F extends (...args: Args) => any +> { + (this: ThisParameterType, ...args: Args): Promise>; cancel: (reason?: any) => void; } -export function debounce( +interface DebouncedPromise { + resolve: (result: FunctionReturn) => void; + reject: (reason?: any) => void; +} + +export function debounce< + Args extends unknown[], + F extends (...args: Args) => any +>( func: F, waitMilliseconds = 50, options: Options> = {} -): DebouncedFunction { +): DebouncedFunction { let timeoutId: ReturnType | undefined; const isImmediate = options.isImmediate ?? false; const callback = options.callback ?? false; const maxWait = options.maxWait; let lastInvokeTime = Date.now(); - let promises: { - resolve: (x: ReturnType) => void; - reject: (reason?: any) => void; - }[] = []; + let promises: DebouncedPromise>[] = []; function nextInvokeTimeout() { if (maxWait !== undefined) { @@ -44,7 +47,7 @@ export function debounce( const debouncedFunction = function ( this: ThisParameterType, - ...args: Parameters + ...args: Args ) { const context = this; return new Promise>((resolve, reject) => {