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
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 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.