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

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { DataSource } from 'typeorm';

Per-tenant database connections in NestJS

multi-tenancy connection-pooling dependency-injection
Advanced 8 steps

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