2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-11-22 06:11:20 -05:00
|
|
|
// This module is vendored from std/async/delay.ts
|
2023-02-14 11:38:45 -05:00
|
|
|
// (with some modifications)
|
|
|
|
|
2023-12-08 04:00:03 -05:00
|
|
|
import { primordials } from "ext:core/mod.js";
|
|
|
|
const {
|
|
|
|
Promise,
|
|
|
|
PromiseReject,
|
|
|
|
} = primordials;
|
2023-06-27 02:18:22 -04:00
|
|
|
|
2024-01-10 17:37:25 -05:00
|
|
|
import { clearTimeout, setTimeout } from "ext:deno_web/02_timers.js";
|
|
|
|
|
2023-02-14 11:38:45 -05:00
|
|
|
/** Resolve a Promise after a given amount of milliseconds. */
|
|
|
|
export function delay(
|
|
|
|
ms: number,
|
|
|
|
options: { signal?: AbortSignal } = {},
|
|
|
|
): Promise<void> {
|
|
|
|
const { signal } = options;
|
|
|
|
if (signal?.aborted) {
|
2023-12-08 04:00:03 -05:00
|
|
|
return PromiseReject(signal.reason);
|
2023-02-14 11:38:45 -05:00
|
|
|
}
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const abort = () => {
|
|
|
|
clearTimeout(i);
|
2023-12-08 04:00:03 -05:00
|
|
|
reject(signal!.reason);
|
2023-02-14 11:38:45 -05:00
|
|
|
};
|
|
|
|
const done = () => {
|
|
|
|
signal?.removeEventListener("abort", abort);
|
|
|
|
resolve();
|
|
|
|
};
|
|
|
|
const i = setTimeout(done, ms);
|
|
|
|
signal?.addEventListener("abort", abort, { once: true });
|
|
|
|
});
|
|
|
|
}
|