UNPKG

rc-js-util

Version:

A collection of TS and C++ utilities to help writing performant and correct applications, achieved through strict typing and (removable) invariant checking.

51 lines 1.78 kB
import { fpIdentity } from "../../fp/impl/fp-identity.js"; /** * @public */ export var EResolutionState; (function (EResolutionState) { EResolutionState[EResolutionState["Resolved"] = 0] = "Resolved"; EResolutionState[EResolutionState["TimedOut"] = 1] = "TimedOut"; EResolutionState[EResolutionState["Cancelled"] = 2] = "Cancelled"; })(EResolutionState || (EResolutionState = {})); /** * @public * @param predicate - Once true, the poll finishes. Exceptions are not supported. * @param pollInterval - In milliseconds, defaults to smallest (probably 4 ms). * @param maxTicks - The number of times to run the poll before giving up. */ export function promisePoll(predicate, pollInterval = undefined, maxTicks = Infinity) { return new PromisePoll(predicate, pollInterval, maxTicks); } class PromisePoll { constructor(callback, timeout, maxTicks) { this.callback = callback; this.timeout = timeout; this.maxTicks = maxTicks; this.resolve = fpIdentity; this.id = null; this.tickCount = 0; this.promise = new Promise((resolve) => { this.resolve = resolve; this.id = setInterval(() => { if (this.tickCount++ >= this.maxTicks) { this.cancel(EResolutionState.TimedOut); } else if (this.callback()) { this.cancel(EResolutionState.Resolved); } }, this.timeout); }); } getPromise() { return this.promise; } cancel(reason = EResolutionState.Cancelled) { if (this.id != null) { clearInterval(this.id); this.id = null; this.resolve(reason); } } } //# sourceMappingURL=promise-poll.js.map