UNPKG

@oxog/delay

Version:

A comprehensive, zero-dependency delay/timeout utility library with advanced timing features

75 lines 2.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CancellationToken = void 0; exports.createCancellableDelay = createCancellableDelay; const index_js_1 = require("../types/index.js"); const delay_js_1 = require("./delay.js"); function createCancellableDelay(ms, options = {}) { const controller = new AbortController(); let isCancelled = false; const delayPromise = (0, delay_js_1.createBasicDelay)(ms, { ...options, signal: controller.signal, }); const cancellablePromise = Object.assign(delayPromise, { cancel() { if (!isCancelled) { isCancelled = true; controller.abort(); } }, isCancelled() { return isCancelled; }, }); // Handle the case where the original signal is already aborted if (options.signal?.aborted) { isCancelled = true; controller.abort(); } // Listen for abort on the original signal options.signal?.addEventListener('abort', () => { isCancelled = true; controller.abort(); }); return cancellablePromise; } class CancellationToken { constructor() { this._isCancelled = false; this._callbacks = []; } get isCancelled() { return this._isCancelled; } cancel() { if (!this._isCancelled) { this._isCancelled = true; this._callbacks.forEach(callback => { try { callback(); } catch (error) { // Ignore callback errors to prevent one bad callback from affecting others console.error('Error in cancellation callback:', error); } }); this._callbacks.length = 0; } } onCancel(callback) { if (this._isCancelled) { callback(); } else { this._callbacks.push(callback); } } throwIfCancelled() { if (this._isCancelled) { throw new index_js_1.DelayError('Operation was cancelled', index_js_1.DelayErrorCode.CANCELLED); } } } exports.CancellationToken = CancellationToken; //# sourceMappingURL=cancellable.js.map