import { Logger } from '@stackbit/types'; export class Timer { private readonly timerCallback: () => void; private readonly timerMs: number; private readonly logger?: Logger; private timeout: NodeJS.Timeout | null; constructor({ timerCallback, timerMs = 30 * 60 * 1000, logger }: { timerCallback: () => void; timerMs?: number; logger?: Logger }) { this.timerCallback = timerCallback; this.timerMs = timerMs; this.logger = logger?.createLogger({ label: 'timer' }); this.timeout = null; this.handleTimeout = this.handleTimeout.bind(this); } isRunning() { return !!this.timeout; } startTimer() { this.resetTimer(); } resetTimer() { this.stopTimer(); this.timeout = setTimeout(this.handleTimeout, this.timerMs); } stopTimer() { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } } handleTimeout() { this.logger?.debug('timer reached'); this.timeout = null; this.timerCallback(); } }