UNPKG

@thi.ng/rstream

Version:

Reactive streams & subscription primitives for constructing dataflow graphs / pipelines

45 lines (44 loc) 1.03 kB
import { State } from "./api.js"; import { __optsWithID } from "./idgen.js"; import { Subscription } from "./subscription.js"; const timeout = (timeoutMs, opts) => new Timeout(timeoutMs, opts); class Timeout extends Subscription { timeoutMs; timeoutId; errorObj; resetTimeout; constructor(timeoutMs, opts) { opts = __optsWithID("timeout", opts); super(void 0, opts); this.timeoutMs = timeoutMs; this.errorObj = opts.error; this.resetTimeout = opts.reset === true; this.reset(); } next(x) { if (this.resetTimeout) { clearTimeout(this.timeoutId); this.reset(); } super.next(x); } reset() { this.timeoutId = setTimeout(() => { if (this.state < State.DONE) { this.dispatchTo( "error", this.errorObj || new Error( `Timeout '${this.id}' after ${this.timeoutMs} ms` ) ); } }, this.timeoutMs); } release() { clearTimeout(this.timeoutId); super.release(); } } export { timeout };