javascript
36 lines · 6 steps
Polling a job until it finishes in JavaScript
An async loop that repeatedly checks a job's status, with timeout and cancellation support.
Explained by
highlit
1async function pollJobUntilComplete(jobId, { interval = 2000, timeout = 60000, signal } = {}) {
2 const deadline = Date.now() + timeout;
3
4 while (true) {
5 const res = await fetch(`/api/jobs/${jobId}`, { signal });
6 if (!res.ok) {
7 throw new Error(`Failed to fetch job ${jobId}: ${res.status}`);
8 }
9
10 const job = await res.json();
11
12 switch (job.status) {
13 case 'completed':
14 return job.result;
15 case 'failed':
16 throw new Error(job.error || `Job ${jobId} failed`);
17 case 'pending':
18 case 'running':
19 break;
20 default:
21 throw new Error(`Unexpected status for job ${jobId}: ${job.status}`);
22 }
23
24 if (Date.now() + interval >= deadline) {
25 throw new Error(`Timed out waiting for job ${jobId} after ${timeout}ms`);
26 }
27
28 await new Promise((resolve, reject) => {
29 const timer = setTimeout(resolve, interval);
30 signal?.addEventListener('abort', () => {
31 clearTimeout(timer);
32 reject(new DOMException('Polling aborted', 'AbortError'));
33 }, { once: true });
34 });
35 }
36}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A while-true loop with await turns repeated network checks into readable sequential code.
- 2Threading an AbortSignal through both fetch and the delay makes the whole poll cancellable.
- 3Checking the deadline before sleeping avoids one pointless final wait past the timeout.
Related explainers
go
package main import ( "errors"
Parsing and validating CLI flags in Go
cli-parsing
validation
error-handling
Intermediate
8 steps
javascript
'use server' import { revalidatePath } from 'next/cache' import { redirect } from 'next/navigation'
How a Next.js Server Action updates a post
server-actions
authorization
validation
Intermediate
7 steps
java
public class ThumbnailProcessor { private static final int MAX_CONCURRENCY = 4;
Bounded parallel thumbnail rendering in Java
concurrency
thread-pool
futures
Intermediate
7 steps
typescript
type RetryOptions = { retries?: number; timeoutMs?: number; baseDelayMs?: number;
Retry with timeout and backoff in TypeScript
promises
retry
exponential-backoff
Intermediate
10 steps
javascript
const express = require('express'); const v1 = express.Router();
Versioning an API with Express Routers
api versioning
routing
modularity
Intermediate
10 steps
javascript
const RATE_LIMIT = 100; const WINDOW_MS = 60 * 1000; const BLOCK_MS = 5 * 60 * 1000;
Building a rate-limiting middleware in Express
rate-limiting
middleware
closures
Intermediate
9 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/polling-a-job-until-it-finishes-in-javascript-explained-javascript-46be/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.