UNPKG

@reactivex/ix-esnext-esm

Version:

The Interactive Extensions for JavaScript

46 lines (44 loc) 1.35 kB
import { AsyncIterableX } from '../asynciterablex'; import { sleep } from '../_sleep'; export class TimeoutError extends Error { constructor() { super(); Object.setPrototypeOf(this, TimeoutError.prototype); this.message = 'Timeout has occurred'; } } const VALUE_TYPE = 'value'; const ERROR_TYPE = 'error'; export class TimeoutAsyncIterable extends AsyncIterableX { constructor(source, dueTime) { super(); this._source = source; this._dueTime = dueTime; } async *[Symbol.asyncIterator]() { const it = this._source[Symbol.asyncIterator](); while (1) { const { type, value } = await Promise.race([ it.next().then(val => { return { type: VALUE_TYPE, val }; }), sleep(this._dueTime).then(() => { return { type: ERROR_TYPE }; }) ]); if (type === ERROR_TYPE) { throw new TimeoutError(); } if (!value || value.done) { break; } yield value.value; } } } export function timeout(dueTime) { return function timeoutOperatorFunction(source) { return new TimeoutAsyncIterable(source, dueTime); }; } //# sourceMappingURL=timeout.mjs.map