Skip to content

Instantly share code, notes, and snippets.

@jcayzac
Created November 24, 2022 06:56
Show Gist options
  • Save jcayzac/035f195423a06261d60afe10dfab8668 to your computer and use it in GitHub Desktop.
Save jcayzac/035f195423a06261d60afe10dfab8668 to your computer and use it in GitHub Desktop.
The ultimate sleep() method for Typescript
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