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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Generics let one polling loop serve any fetch shape while keeping return types precise.
- 2Wrapping setTimeout in a promise that also listens for abort makes delays cleanly cancellable.
- 3Checking the deadline before sleeping avoids waiting out a full interval you know will exceed the budget.
Related explainers
rust
use std::time::Duration; use tokio::time::sleep; #[derive(Debug)]
Async retry with exponential backoff in Rust
retry
exponential-backoff
async
Intermediate
8 steps
rust
use std::fs; use std::io; use std::path::{Path, PathBuf};
Recursive file search by extension in Rust
recursion
filesystem
error-handling
Intermediate
8 steps
typescript
type Ok<T> = { ok: true; value: T }; type Err<E> = { ok: false; error: E }; export type Result<T, E> = Ok<T> | Err<E>;
A Result type for typed error handling
discriminated-union
error-handling
type-guards
Intermediate
8 steps
java
public final class RetryExecutor { private final int maxAttempts; private final Duration initialDelay;
Exponential backoff retry in Java
retry
exponential-backoff
jitter
Intermediate
8 steps
typescript
import { ArgumentsHost, Catch, ExceptionFilter,
A catch-all exception filter in NestJS
error-handling
exception-filter
http
Intermediate
8 steps
typescript
import { Module, Injectable } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import * as Joi from 'joi';
Validated, typed config in NestJS
configuration
validation
dependency-injection
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-cancellable-polling-helper-in-typescript-explained-typescript-caae/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.