@oxog/delay
Version:
A comprehensive, zero-dependency delay/timeout utility library with advanced timing features
132 lines • 3.67 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RepeatManager = void 0;
exports.createRepeatDelay = createRepeatDelay;
exports.createIntervalDelay = createIntervalDelay;
const validation_js_1 = require("../utils/validation.js");
function createRepeatDelay(fn, interval) {
(0, validation_js_1.validateFunction)(fn, 'repeat function');
(0, validation_js_1.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;
},
};
}
function createIntervalDelay(fn, interval) {
(0, validation_js_1.validateFunction)(fn, 'interval function');
(0, validation_js_1.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;
},
};
}
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);
}
});
}
}
exports.RepeatManager = RepeatManager;
//# sourceMappingURL=repeat.js.map