import type { Falsy } from "../core/index.js"; export interface PollFn { (abort: AbortSignal): T | Falsy | Promise; } export class PollTimeoutError extends Error {} /** * Repeatedly call a function until a truthy value is returned. * * + The function is called at most every event cycle. * + If a timeout occurs, a {@link PollTimeoutError} is thrown and the abort signal passed to the function is aborted with the same error. * * @param fn The function to run. * @param timeout An optional timeout. * @returns The first truthy value. */ export async function poll(fn: PollFn, timeout?: number): Promise { const ac = new AbortController(); let timer: undefined | number; if (timeout !== undefined) { timer = setTimeout(() => ac.abort(new PollTimeoutError()), timeout); } try { for (;;) { const value = await fn(ac.signal); if (value) { return value as T; } ac.signal.throwIfAborted(); await new Promise(r => setTimeout(r, 0)); } } finally { clearTimeout(timer); } }