@johngw/stream
Version:
Reactive programming tools using the WHATWG Streams API.
49 lines • 1.13 kB
JavaScript
/**
* 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
* })
*/
export function timeout(ms) {
let timer;
return new TransformStream({
start: (controller) => {
begin(controller);
},
transform(chunk, controller) {
begin(controller);
controller.enqueue(chunk);
},
flush() {
clearTimeout(timer);
},
cancel() {
clearTimeout(timer);
},
});
function begin(controller) {
clearTimeout(timer);
timer = setTimeout(() => controller.error(new TimeoutError(ms)), ms);
}
}
/**
* The error emitted from {@link timeout}.
*
* @group Transformers
*/
export class TimeoutError extends Error {
ms;
constructor(ms) {
super(`Exceeded ${ms}ms`);
this.ms = ms;
}
}
//# sourceMappingURL=timeout.js.map