UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

51 lines 1.24 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TimeoutError = exports.timeout = void 0; /** * Makes sure that events are emitted within `ms`. * Otherwise emits an error. * * @group Transformers * @throws {@link TimeoutError} * @example * readableStream * .pipeThrough(timeout(1_000)) * .pipeTo(write()) * .catch(error => { * // error is TimeoutError if any event took too long * }) */ function timeout(ms) { let timer; return new TransformStream({ start: (controller) => { begin(controller); }, transform(chunk, controller) { begin(controller); controller.enqueue(chunk); }, flush() { clearTimeout(timer); }, }); function begin(controller) { clearTimeout(timer); timer = setTimeout(() => controller.error(new TimeoutError(ms)), ms); } } exports.timeout = timeout; /** * The error emitted from {@link timeout}. * * @group Transformers */ class TimeoutError extends Error { ms; constructor(ms) { super(`Exceeded ${ms}ms`); this.ms = ms; } } exports.TimeoutError = TimeoutError; //# sourceMappingURL=timeout.js.map