async-wrappers
Version:
A set of wrapper functions to perform debouncing, throttling, retrying etc.
79 lines (78 loc) • 2.77 kB
TypeScript
import { CallFunction } from './callReduce';
import { ReducerCallParameters, ReducerFunction } from './callReducers';
/**
* Options for [[debounce]]
*
* @typeparam Reducer an [[ArgumentsReducer]]
*
* @category Debounce
*/
export interface DebounceOptions<Reducer> {
/**
* Used to create the arguments to `fn` when it is
* executed. It is run for every call of the debounced function. The default
* implementation is to execute `func` with the latest arguments.
*/
reducer?: Reducer;
/**
* The maximum number of milliseconds before the function will
* be executed. If execution has not happened as calls are still occuring then
* this the maximum number of milliseconds allowed to pass before the function
* will be executed.
*/
maxDelay?: number;
/**
* The maximum number of calls before the function will
* be executed
*/
maxCalls?: number;
/**
* If supplied this function will be called if the debounced function is cancelled
* defaults
*/
onCancel?: () => any;
}
/**
* A debounced function
*
* @category Debounce
*/
export interface Debounced<F extends (...args: any[]) => any, R extends ReducerFunction<F, any>> extends CallFunction<F, ReducerCallParameters<R>> {
/**
* Cancels pending function execution.
* Pending results will be rejected.
* @param reason Optional reason to reject results with.
*/
cancel(reason?: Error): void;
/**
* Causes any pending execution to fire on next runtime loop
* Subsequent calls will not defer this execution
*/
flush(): void;
}
/**
* Ensure multiple calls to a function will only execute it when it has been
* inactive (no more calls) for a specified delay.
*
* Execution always happens asynchronously.
*
* If the delay is `0` execution will be scheduled to occur after the current
* runtime event loop.
*
* The debounced function returns a promise that resolves to the return value
* of `func`.
*
* By default the arguments to `func` are the latest arguments given to the
* debounced function. For custom behaviour pass an `argumentsReducer`
* function.
*
* @param fn The function to debounce
* @param delay The number of milliseconds on inactivity before the function
* will be executed.
.
* @return the debounced function
*
* @category Wrapper
*/
declare const debounce: <Invoke extends (...args: any[]) => any, Reducer extends import("./callReducers").ArgumentsReducer<Parameters<Invoke>, any> = import("./callReducers").ArgumentsReducer<Parameters<Invoke>, import("./callReducers").ParametersOrArray<Invoke>>>(fn: Invoke, delay?: number, options?: DebounceOptions<Reducer>) => Debounced<Invoke, Reducer>;
export default debounce;