Skip to content

Instantly share code, notes, and snippets.

@LXSMNSYC
Last active Oct 13, 2020
Embed
What would you like to do?
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;
}
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