mirror of
https://github.com/denoland/std.git
synced 2024-11-22 04:59:05 +00:00
27 lines
827 B
TypeScript
27 lines
827 B
TypeScript
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
|
|
// This module is browser compatible.
|
|
|
|
export interface DelayOptions {
|
|
signal?: AbortSignal;
|
|
}
|
|
|
|
/* Resolves after the given number of milliseconds. */
|
|
export function delay(ms: number, options: DelayOptions = {}): Promise<void> {
|
|
const { signal } = options;
|
|
if (signal?.aborted) {
|
|
return Promise.reject(new DOMException("Delay was aborted.", "AbortError"));
|
|
}
|
|
return new Promise((resolve, reject): void => {
|
|
const abort = () => {
|
|
clearTimeout(i);
|
|
reject(new DOMException("Delay was aborted.", "AbortError"));
|
|
};
|
|
const done = () => {
|
|
signal?.removeEventListener("abort", abort);
|
|
resolve();
|
|
};
|
|
const i = setTimeout(done, ms);
|
|
signal?.addEventListener("abort", abort, { once: true });
|
|
});
|
|
}
|