* Resolves after the given number of milliseconds using real time. * * @example Usage * ```ts * import { FakeTime } from "@std/testing/time"; * import { assertEquals } from "@std/assert"; * * const fakeTime = new FakeTime(15_000); * * await fakeTime.delay(500); // wait 500
(ms: number, options: DelayOptions = {})
| 569 | * @param options The options |
| 570 | */ |
| 571 | async delay(ms: number, options: DelayOptions = {}): Promise<void> { |
| 572 | const { signal } = options; |
| 573 | if (signal?.aborted) { |
| 574 | return Promise.reject( |
| 575 | new DOMException("Delay was aborted.", "AbortError"), |
| 576 | ); |
| 577 | } |
| 578 | return await new Promise((resolve, reject) => { |
| 579 | let timer: ReturnType<typeof setTimeout> | null = null; |
| 580 | const abort = () => |
| 581 | FakeTime |
| 582 | .restoreFor(() => { |
| 583 | if (timer) clearTimeout(timer); |
| 584 | }) |
| 585 | .then(() => |
| 586 | reject(new DOMException("Delay was aborted.", "AbortError")) |
| 587 | ); |
| 588 | const done = () => { |
| 589 | signal?.removeEventListener("abort", abort); |
| 590 | resolve(); |
| 591 | }; |
| 592 | FakeTime.restoreFor(() => setTimeout(done, ms)) |
| 593 | .then((id) => timer = id); |
| 594 | signal?.addEventListener("abort", abort, { once: true }); |
| 595 | }); |
| 596 | } |
| 597 | |
| 598 | /** |
| 599 | * Runs all pending microtasks. |
no test coverage detected