UNPKG

@oxog/delay

Version:

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

126 lines 3.37 kB
import { validateFunction, validateDelay } from '../utils/validation.js'; export function createRepeatDelay(fn, interval) { validateFunction(fn, 'repeat function'); validateDelay(interval); let isRunning = true; let isPaused = false; let timeoutId; const executeNext = async () => { if (!isRunning) { return; } if (!isPaused) { try { await fn(); } catch (error) { // Continue repeating even if the function throws an error console.error('Error in repeat function:', error); } } if (isRunning) { timeoutId = setTimeout(executeNext, interval); } }; // Start the first execution void executeNext(); return { stop() { isRunning = false; if (timeoutId !== undefined) { if (typeof timeoutId === 'number') { clearTimeout(timeoutId); } else { clearTimeout(timeoutId); } timeoutId = undefined; } }, pause() { isPaused = true; }, resume() { isPaused = false; }, isPaused() { return isPaused; }, isStopped() { return !isRunning; }, }; } export function createIntervalDelay(fn, interval) { validateFunction(fn, 'interval function'); validateDelay(interval); let isRunning = true; let isPaused = false; let intervalId; const wrappedFn = async () => { if (!isPaused && isRunning) { try { await fn(); } catch (error) { console.error('Error in interval function:', error); } } }; intervalId = setInterval(wrappedFn, interval); return { stop() { isRunning = false; if (intervalId !== undefined) { if (typeof intervalId === 'number') { clearInterval(intervalId); } else { clearInterval(intervalId); } intervalId = undefined; } }, pause() { isPaused = true; }, resume() { isPaused = false; }, isPaused() { return isPaused; }, isStopped() { return !isRunning; }, }; } export class RepeatManager { constructor() { this.controllers = new Set(); } add(controller) { this.controllers.add(controller); } stopAll() { this.controllers.forEach(controller => controller.stop()); this.controllers.clear(); } pauseAll() { this.controllers.forEach(controller => controller.pause()); } resumeAll() { this.controllers.forEach(controller => controller.resume()); } getActiveCount() { return Array.from(this.controllers).filter(c => !c.isStopped()).length; } cleanup() { this.controllers.forEach(controller => { if (controller.isStopped()) { this.controllers.delete(controller); } }); } } //# sourceMappingURL=repeat.js.map