delay
delay creates a cancellable promise that resolves after the given number of milliseconds. It is the cancellable equivalent of setTimeout for promises.
Best for pauses Use
delaywhen you need to insert a wait between async steps, implement polling intervals, or add rate-limiting pauses in workflows.
Import
Section titled “Import”Root package:
import { delay } from "@vgerbot/async";Module subpath:
import { delay } from "@vgerbot/async/control-flow";Leaf subpath:
import { delay } from "@vgerbot/async/control-flow/delay";Quick example
Section titled “Quick example”import { delay } from "@vgerbot/async";
// Wait 1 secondawait delay(1000);console.log("1 second elapsed");When to use delay
Section titled “When to use delay”- Pauses between steps: Insert a wait between operations without blocking the event loop.
- Polling intervals: Combine with
foreverorwhilstto poll at fixed intervals. - Rate-limiting: Add delays between API calls to respect rate limits.
- Testing: Simulate latency in tests or development environments.
function delay( ms: number, options?: CancellableOptions<void>,): CancellableHandle<void>;Parameters
Section titled “Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
ms |
number |
— | Delay duration in milliseconds. |
options |
CancellableOptions<void> |
undefined |
Cancellable configuration options. |
Return value
Section titled “Return value”Returns a CancellableHandle<void> that resolves after the delay.
const handle = delay(5000);
await handle;handle.cancel("No longer needed");handle.isCancelled();handle.signal;Execution model
Section titled “Execution model”delay is built on cancellable and uses CancellableToken.sleep() internally. The sleep is cooperative—cancellation interrupts the wait immediately.
const handle = delay(10_000);
// Cancel after 1 secondsetTimeout(() => handle.cancel(), 1000);
try { await handle;} catch (error) { console.log("Delay was cancelled");}Cancellation
Section titled “Cancellation”delay supports cancellation through the standard CancellableHandle API. Calling cancel() interrupts the ongoing sleep.
const handle = delay(60_000, { name: "longWait" });
// Cancel from elsewherehandle.cancel("User navigated away");You can also pass an external AbortSignal:
const controller = new AbortController();
const handle = delay(5000, { signal: controller.signal });
controller.abort();TypeScript tips
Section titled “TypeScript tips”delay returns CancellableHandle<void>, so the resolved value is always undefined. Use it in void contexts or chain it with .then().
// Type-safe chainingawait delay(100);const result = await fetch("/api/data");Related APIs
Section titled “Related APIs”timeoutwraps a task with a deadline.cancellablecreates a cancellable handle for custom tasks.foreverruns a task indefinitely until cancelled.whilstrepeats a task while a condition holds.