Created
November 24, 2022 06:56
-
-
Save jcayzac/035f195423a06261d60afe10dfab8668 to your computer and use it in GitHub Desktop.
The ultimate sleep() method for Typescript
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 SleepOptions = { | |
signal?: AbortSignal | |
/** If set, aborting will not fail the promise but instead fulfil it right away. */ | |
skipOnAbort?: true | |
} | |
export const sleep = (ms: number, options?: SleepOptions) => | |
new Promise<void>((ok, ng) => { | |
// deno-lint-ignore prefer-const | |
let timeout: number | |
const abortHandler = () => { | |
clearTimeout(timeout) | |
if (options?.skipOnAbort === true) ok() | |
else { | |
const aborted = new Error(`sleep aborted`) | |
aborted.name = 'AbortError' | |
ng(aborted) | |
} | |
} | |
options?.signal?.addEventListener('abort', abortHandler) | |
timeout = setTimeout(() => { | |
options?.signal?.removeEventListener('abort', abortHandler) | |
ok() | |
}, ms) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment