@stokr/components-library
Version:
STOKR - Components Library
93 lines (87 loc) • 2.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class TimerService {
constructor() {
this.timers = new Map();
this.listeners = new Map();
}
startTimer(timerId, duration, onTick, onExpire) {
// Clear existing timer if it exists
this.stopTimer(timerId);
const startTime = Date.now();
const endTime = startTime + duration * 1000;
const timer = {
startTime,
endTime,
duration,
interval: null,
onTick,
onExpire
};
this.timers.set(timerId, timer);
timer.interval = setInterval(() => {
const now = Date.now();
const elapsed = Math.floor((now - startTime) / 1000);
const remaining = Math.max(0, duration - elapsed);
// Call onTick callback with remaining time
if (onTick) {
onTick(remaining, remaining <= 0);
}
if (remaining <= 0) {
this.stopTimer(timerId);
if (onExpire) {
onExpire();
}
}
}, 1000);
// Initial call
if (onTick) {
onTick(duration, false);
}
}
stopTimer(timerId) {
const timer = this.timers.get(timerId);
if (timer) {
if (timer.interval) {
clearInterval(timer.interval);
}
this.timers.delete(timerId);
}
}
getTimerInfo(timerId) {
const timer = this.timers.get(timerId);
if (!timer) return null;
const now = Date.now();
const elapsed = Math.floor((now - timer.startTime) / 1000);
const remaining = Math.max(0, timer.duration - elapsed);
return {
remaining,
isExpired: remaining <= 0,
isActive: true
};
}
isTimerActive(timerId) {
return this.timers.has(timerId);
}
// Cleanup all timers
cleanup() {
this.timers.forEach(timer => {
if (timer.interval) {
clearInterval(timer.interval);
}
});
this.timers.clear();
}
}
// Singleton instance
const timerService = new TimerService();
// Cleanup on page unload
if (typeof window !== 'undefined') {
window.addEventListener('beforeunload', () => {
timerService.cleanup();
});
}
var _default = exports.default = timerService;