Skip to content

Instantly share code, notes, and snippets.

@sagirk
Last active April 16, 2021 04:43
Show Gist options
  • Save sagirk/f88f1fd91f3fe64e00a7309f4be15b5b to your computer and use it in GitHub Desktop.
Save sagirk/f88f1fd91f3fe64e00a7309f4be15b5b to your computer and use it in GitHub Desktop.
Debounce promise-returning & async functions
/**
* A function that emits a side effect and returns a promise.
*/
type Procedure = (...args: any[]) => Promise<void>;
/**
* `debounceAsync` debounces promise-returning & async functions.
* Adapted from Sindre's p-debounce.
* Ref: https://github.com/sindresorhus/p-debounce
*
* @param functionToDebounce - Promise-returning/async function.
* @param wait - Milliseconds to wait before calling `functionToDebounce` again.
* @returns A function that delays calling `functionToDebounce` until after
* `wait` milliseconds have elapsed since the last time it was called.
*/
function debounceAsync(
functionToDebounce: Procedure,
wait: number = 250
): Procedure {
let timer: NodeJS.Timer | null;
let resolveList: any[] = [];
return (...args) => {
const context = this;
return new Promise(resolve => {
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
const result = functionToDebounce.apply(context, args);
for (resolve of resolveList) {
resolve(result);
}
resolveList = [];
}, wait);
!timer
? resolve(functionToDebounce.apply(context, args))
: resolveList.push(resolve);
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment