import { TimeoutError } from './error/TimeoutError'; import { PredicateC0 } from './Predicate'; /** * Resolve after a set amount of time. * @public */ export function defer(ms: number): Promise { return new Promise((res, _rej) => { setTimeout(() => { res(); }, ms); }); } export function deferValue(ms: number, val: T): Promise { return new Promise((res, _rej) => { setTimeout(() => { res(val); }, ms); }); } /** * Reject after a set amount of time if the original promise has not yet resolved. * @public */ export function timeout(ms: number, oper: Promise): Promise { const limit = new Promise((_res, rej) => { setTimeout(() => { rej(new TimeoutError()); }, ms); }); return Promise.race([limit, oper]); } /** * Reject after a set number of attempts if the given predicate does not return true. * @public * @throws TimeoutError */ export async function waitFor(cb: PredicateC0, step: number, count: number): Promise { let accum = 0; while (accum < count) { await defer(step); if (cb()) { return; } accum += 1; } throw new TimeoutError(); }