Skip to content

Commit

Permalink
Implement manual counter resetting for TimeoutScheduler
Browse files Browse the repository at this point in the history
  • Loading branch information
maxima-net committed Sep 5, 2022
1 parent 6fab5f0 commit 3986f66
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/core/timeoutScheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
Expand All @@ -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];
Expand All @@ -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);
}
Expand Down
28 changes: 28 additions & 0 deletions tests/core/timeoutScheduler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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++;
Expand Down

0 comments on commit 3986f66

Please sign in to comment.