Skip to content

Instantly share code, notes, and snippets.

@lxsmnsyc
Last active October 13, 2020 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lxsmnsyc/7935c5db4d935f71a2107bf0edccb85e to your computer and use it in GitHub Desktop.
Save lxsmnsyc/7935c5db4d935f71a2107bf0edccb85e to your computer and use it in GitHub Desktop.
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