diff --git a/src/core/timeoutScheduler.ts b/src/core/timeoutScheduler.ts index b22efe6..de01b50 100644 --- a/src/core/timeoutScheduler.ts +++ b/src/core/timeoutScheduler.ts @@ -7,7 +7,7 @@ export class TimeoutScheduler implements Disposable { constructor( private readonly timeouts: number[], - private readonly counterExpirationMs: number + private readonly counterExpirationMs?: number ) { } async dispose(): Promise { @@ -19,7 +19,8 @@ export class TimeoutScheduler implements Disposable { } setTimeout(action: () => void) { - this.resetCounterExpiration(); + if (this.counterExpirationMs) + this.resetCounterExpiration(); const timeoutIndex = Math.min(this.actionCounter, this.timeouts.length - 1); const timeout = this.timeouts[timeoutIndex]; @@ -28,12 +29,16 @@ export class TimeoutScheduler implements Disposable { this.actionCounter++; } + resetCounter() { + this.actionCounter = 0; + } + private resetCounterExpiration() { if (this.counterExpirationWatcherId) clearInterval(this.counterExpirationWatcherId); this.counterExpirationWatcherId = setTimeout(() => { - this.actionCounter = 0; + this.resetCounter(); this.counterExpirationWatcherId = undefined; }, this.counterExpirationMs); } diff --git a/tests/core/timeoutScheduler.test.ts b/tests/core/timeoutScheduler.test.ts index 48b7235..610ca5c 100644 --- a/tests/core/timeoutScheduler.test.ts +++ b/tests/core/timeoutScheduler.test.ts @@ -8,6 +8,34 @@ describe('TimeoutScheduler', () => { scheduler.dispose(); }); + test('runs scheduled actions and clears timer', async () => { + let counter = 0; + const action = () => counter++; + + scheduler = new TimeoutScheduler([500, 700]); + + scheduler.setTimeout(action); + await wait(500); + expect(counter).toEqual(1); + + scheduler.setTimeout(action); + await wait(500); + expect(counter).toEqual(1); + await wait(200); + expect(counter).toEqual(2); + + scheduler.setTimeout(action); + await wait(500); + expect(counter).toEqual(2); + await wait(200); + expect(counter).toEqual(3); + + scheduler.resetCounter(); + scheduler.setTimeout(action); + await wait(500); + expect(counter).toEqual(4); + }); + test('runs scheduled actions and clears timer automatically', async () => { let counter = 0; const action = () => counter++;