This file contains 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
export type AsyncCallback<T extends any[]> = (...args: T) => Promise<void>; | |
export type DebouncedAsync<T extends any[]> = (...args: T) => void; | |
export function debounceAsync<T extends any[]>(callback: AsyncCallback<T>, duration: number): DebouncedAsync<T> { | |
let lifecycle: PromiseLifecycle; | |
let timeout: number; | |
function control(...args: T) { | |
if (timeout) { | |
lifecycle.alive = false; | |
window.clearTimeout(timeout); | |
} | |
lifecycle = { | |
alive: true, | |
}; | |
timeout = window.setTimeout(() => { | |
promiseLifecycle(lifecycle, callback.call(null, ...args)); | |
}, duration); | |
} | |
return control; | |
} |
This file contains 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
export interface PromiseLifecycle { | |
alive: boolean; | |
} | |
export function promiseLifecycle<T>( | |
lifecycle: PromiseLifecycle, | |
promise: Promise<T>, | |
): Promise<T> { | |
return new Promise<T>((resolve, reject) => { | |
promise.then( | |
(value) => { | |
if (lifecycle.alive) { | |
resolve(value); | |
} | |
}, | |
(value) => { | |
if (lifecycle.alive) { | |
reject(value); | |
} | |
}, | |
); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment