Skip to main content

Import

import { PollingHelper, createPoller } from "bytekit/polling-helper";

What it does

PollingHelper repeatedly calls an async function on a schedule until a stop condition is met, a limit is reached, or the caller aborts. It supports exponential and linear backoff, jitter, per-attempt timeouts, and lifecycle hooks.

Constructor

const poller = new PollingHelper<T>(fn: () => Promise<T>, options?: PollingOptions<T>);

PollingOptions<T>

PropertyTypeDefaultDescription
intervalnumber1000Base interval between attempts (ms).
maxAttemptsnumberInfinityMaximum number of attempts.
maxDurationnumberInfinityMaximum total polling duration (ms).
backoffMultipliernumber1Multiplier applied to interval after each attempt.
maxBackoffIntervalnumber30000Upper bound for the computed interval.
exponentialBasenumber2Base for exponential backoff calculation.
jitterfalse | numberfalseAdd random jitter. false disables it; a number 0–100 sets the jitter percentage.
attemptTimeoutnumberTimeout per individual attempt (ms).
retryOnErrorbooleantrueContinue polling when an attempt throws.
stopCondition(result: T) => booleanReturn true to stop polling early.
onAttempt(attempt: number) => voidCalled before each attempt.
onSuccess(result: T) => voidCalled when an attempt succeeds.
onError(error: Error) => voidCalled when an attempt fails.

Instance methods

MethodReturnsDescription
start()Promise<PollingResult<T>>Run the polling loop until completion.
startWithAbort()Promise<PollingResult<T>>Same as start(), but can be cancelled via abort().
abort()voidCancel a running poll started with startWithAbort().

PollingResult<T>

PropertyTypeDescription
successbooleanWhether polling ended with a fulfilled stop condition.
resultT | undefinedLast successful result.
errorError | undefinedLast error, if any.
attemptsnumberTotal attempts executed.
durationnumberTotal elapsed time (ms).
metricsobject | undefinedResponse-time statistics (see below).

metrics

PropertyType
minResponseTimenumber
maxResponseTimenumber
avgResponseTimenumber

Static methods

MethodDescription
PollingHelper.poll(fn, options?)One-shot poll using default options.
PollingHelper.pollWithBackoff(fn, options?)Poll with exponential backoff pre-configured.
PollingHelper.pollWithLinearBackoff(fn, options?)Poll with linear backoff pre-configured.

Factory

const poller = createPoller(fn, options?);
Returns a PollingHelper instance — useful when you want to configure once and call start() later.

Examples

Basic polling with stop condition

import { PollingHelper } from "bytekit/polling-helper";

const poller = new PollingHelper(
  () => fetch("/api/jobs/42").then((r) => r.json()),
  {
    interval: 3000,
    maxAttempts: 20,
    stopCondition: (job) => job.status === "done",
  }
);

const { success, result, attempts } = await poller.start();

Exponential backoff with jitter

const poller = new PollingHelper(checkDeploy, {
  interval: 1000,
  backoffMultiplier: 2,
  maxBackoffInterval: 30_000,
  jitter: 25,
  maxDuration: 120_000,
  stopCondition: (r) => r.ready,
});

const outcome = await poller.start();

Abortable polling

const poller = new PollingHelper(fetchStatus, {
  interval: 5000,
  stopCondition: (s) => s.complete,
});

// Start in background
const promise = poller.startWithAbort();

// Cancel from outside
setTimeout(() => poller.abort(), 60_000);

const result = await promise;

Static shorthand

import { PollingHelper } from "bytekit/polling-helper";

const result = await PollingHelper.pollWithBackoff(
  () => checkProvisioningStatus(),
  {
    maxAttempts: 10,
    stopCondition: (r) => r.provisioned,
  }
);

Lifecycle hooks

const poller = new PollingHelper(fetchMetrics, {
  interval: 2000,
  maxAttempts: 15,
  stopCondition: (m) => m.healthy,
  onAttempt: (n) => console.log(`Attempt ${n}`),
  onSuccess: (m) => console.log("Latest:", m),
  onError: (err) => console.warn("Failed:", err.message),
});
Use jitter in production to avoid thundering-herd problems when many clients poll the same endpoint.