std/async/delay.ts

65 lines
1.7 KiB
TypeScript
Raw Normal View History

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
/** Options for {@linkcode delay}. */
export interface DelayOptions {
2022-11-25 11:40:23 +00:00
/** Signal used to abort the delay. */
signal?: AbortSignal;
2022-11-25 11:40:23 +00:00
/** Indicates whether the process should continue to run as long as the timer exists.
*
* @default {true}
*/
persistent?: boolean;
}
2022-11-25 11:40:23 +00:00
/**
* Resolve a {@linkcode Promise} after a given amount of milliseconds.
2022-11-25 11:40:23 +00:00
*
* @example
* ```ts
2022-11-25 11:40:23 +00:00
* import { delay } from "https://deno.land/std@$STD_VERSION/async/delay.ts";
*
* // ...
* const delayedPromise = delay(100);
* const result = await delayedPromise;
* // ...
* ```
*
* To allow the process to continue to run as long as the timer exists.
2022-11-25 11:40:23 +00:00
*
* ```ts
2022-11-25 11:40:23 +00:00
* import { delay } from "https://deno.land/std@$STD_VERSION/async/delay.ts";
*
* // ...
* await delay(100, { persistent: false });
* // ...
* ```
*/
export function delay(ms: number, options: DelayOptions = {}): Promise<void> {
const { signal, persistent = true } = options;
if (signal?.aborted) return Promise.reject(signal.reason);
return new Promise((resolve, reject) => {
const abort = () => {
clearTimeout(i);
reject(signal?.reason);
};
const done = () => {
signal?.removeEventListener("abort", abort);
resolve();
};
const i = setTimeout(done, ms);
signal?.addEventListener("abort", abort, { once: true });
if (persistent === false) {
try {
// @ts-ignore For browser compatibility
Deno.unrefTimer(i);
} catch (error) {
if (!(error instanceof ReferenceError)) {
throw error;
}
console.error("`persistent` option is only available in Deno");
}
}
});
}