Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions async/delay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ export interface DelayOptions {
persistent?: boolean;
}

// Make type available in browser environments; we catch the `ReferenceError` below
declare const Deno: { unrefTimer(id: number): void };

/**
* Resolve a {@linkcode Promise} after a given amount of milliseconds.
*
Expand Down Expand Up @@ -59,10 +62,10 @@ export function delay(ms: number, options: DelayOptions = {}): Promise<void> {
signal?.addEventListener("abort", abort, { once: true });
if (persistent === false) {
try {
// @ts-ignore For browser compatibility
Deno.unrefTimer(i);
Deno.unrefTimer(+i);
} catch (error) {
if (!(error instanceof ReferenceError)) {
clearTimeout(+i);
throw error;
}
// deno-lint-ignore no-console
Expand Down
27 changes: 17 additions & 10 deletions async/delay_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,14 @@ Deno.test("delay() handles already aborted signal", async () => {
});

Deno.test("delay() handles persistent option", async () => {
using unrefTimer = stub(Deno, "unrefTimer");
await delay(100, { persistent: false });
// Stub with itself to ensure the actual function is still called, but we can track calls
using unrefTimer = stub(Deno, "unrefTimer", Deno.unrefTimer);

await Promise.all([
delay(0, { persistent: false }),
// Longer, persistent timer to ensure the process doesn't actually exit early (this would cause a test failure)
delay(1),
]);
assertSpyCalls(unrefTimer, 1);
});

Expand All @@ -125,15 +131,16 @@ Deno.test({
name: "delay() handles persistent option with error",
async fn() {
using unrefTimer = stub(Deno, "unrefTimer", () => {
throw new Error("Error!");
throw new TypeError("Error!");
});
try {
await delay(100, { persistent: false });
} catch (e) {
assert(e instanceof Error);
assertEquals(e.message, "Error!");
assertSpyCalls(unrefTimer, 1);
}

await assertRejects(
() => delay(100, { persistent: false }),
TypeError,
"Error!",
);

assertSpyCalls(unrefTimer, 1);
},
sanitizeResources: false,
sanitizeOps: false,
Expand Down
Loading