typescript 58 lines · 9 steps

A cancellable polling helper in TypeScript

A generic pollUntil repeatedly fetches until a condition holds, respecting a timeout and an AbortSignal.

Explained by highlit
1interface PollOptions<T> {
2 intervalMs?: number;
3 timeoutMs?: number;
4 signal?: AbortSignal;
5}
6 
7export async function pollUntil<T>(
8 fetchFn: () => Promise<T>,
9 isDone: (value: T) => boolean,
10 { intervalMs = 2000, timeoutMs = 60000, signal }: PollOptions<T> = {},
11): Promise<T> {
12 const deadline = Date.now() + timeoutMs;
13 
14 while (true) {
15 if (signal?.aborted) {
16 throw new DOMException("Polling aborted", "AbortError");
17 }
18 
19 const value = await fetchFn();
20 if (isDone(value)) {
21 return value;
22 }
23 
24 if (Date.now() + intervalMs >= deadline) {
25 throw new Error(`Condition not met within ${timeoutMs}ms`);
26 }
27 
28 await delay(intervalMs, signal);
29 }
30}
31 
32function delay(ms: number, signal?: AbortSignal): Promise<void> {
33 return new Promise((resolve, reject) => {
34 const timer = setTimeout(() => {
35 signal?.removeEventListener("abort", onAbort);
36 resolve();
37 }, ms);
38 
39 const onAbort = () => {
40 clearTimeout(timer);
41 reject(new DOMException("Polling aborted", "AbortError"));
42 };
43 
44 signal?.addEventListener("abort", onAbort, { once: true });
45 });
46}
47 
48export async function waitForJob(jobId: string): Promise<Job> {
49 return pollUntil(
50 async () => {
51 const res = await fetch(`/api/jobs/${jobId}`);
52 if (!res.ok) throw new Error(`Job fetch failed: ${res.status}`);
53 return (await res.json()) as Job;
54 },
55 (job) => job.status === "completed" || job.status === "failed",
56 { intervalMs: 1500, timeoutMs: 120000 },
57 );
58}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Generics let one polling loop serve any fetch shape while keeping return types precise.
  2. 2Wrapping setTimeout in a promise that also listens for abort makes delays cleanly cancellable.
  3. 3Checking the deadline before sleeping avoids waiting out a full interval you know will exceed the budget.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A cancellable polling helper in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code