Last active
April 16, 2021 04:43
-
-
Save sagirk/f88f1fd91f3fe64e00a7309f4be15b5b to your computer and use it in GitHub Desktop.
Debounce promise-returning & async functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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