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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
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.