Skip to content

Commit

Permalink
Add counter prop
Browse files Browse the repository at this point in the history
  • Loading branch information
maxima-net committed Sep 6, 2022
1 parent 51eaf5c commit 21efdb8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/core/timeoutScheduler.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import type { Disposable } from '../common';

export class TimeoutScheduler implements Disposable {
private counter = 0;
private counterExpirationWatcherId: ReturnType<typeof setTimeout> | undefined;
private actionWatcherId: ReturnType<typeof setTimeout> | undefined;
private _counter = 0;

constructor(
private readonly timeouts: number[],
private readonly counterExpirationMs?: number
) { }

get counter() {
return this._counter;
}

private set counter(value: number) {
this._counter = value;
}

async dispose(): Promise<void> {
if (this.counterExpirationWatcherId)
clearInterval(this.counterExpirationWatcherId);
Expand Down
12 changes: 12 additions & 0 deletions tests/core/timeoutScheduler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,32 @@ describe('TimeoutScheduler', () => {

scheduler = new TimeoutScheduler([500, 700]);

expect(scheduler.counter).toEqual(0);
scheduler.setTimeout(action);
await wait(500);
expect(counter).toEqual(1);
expect(scheduler.counter).toEqual(1);

scheduler.setTimeout(action);
await wait(500);
expect(counter).toEqual(1);
await wait(200);
expect(counter).toEqual(2);
expect(scheduler.counter).toEqual(2);

scheduler.setTimeout(action);
await wait(500);
expect(counter).toEqual(2);
await wait(200);
expect(counter).toEqual(3);
expect(scheduler.counter).toEqual(3);

scheduler.resetCounter();
expect(scheduler.counter).toEqual(0);
scheduler.setTimeout(action);
await wait(500);
expect(counter).toEqual(4);
expect(scheduler.counter).toEqual(1);
});

test('runs scheduled actions and clears timer automatically', async () => {
Expand All @@ -42,26 +48,32 @@ describe('TimeoutScheduler', () => {

scheduler = new TimeoutScheduler([500, 700], 1000);

expect(scheduler.counter).toEqual(0);
scheduler.setTimeout(action);
await wait(500);
expect(counter).toEqual(1);
expect(scheduler.counter).toEqual(1);

scheduler.setTimeout(action);
await wait(500);
expect(counter).toEqual(1);
await wait(200);
expect(counter).toEqual(2);
expect(scheduler.counter).toEqual(2);

scheduler.setTimeout(action);
await wait(500);
expect(counter).toEqual(2);
await wait(200);
expect(counter).toEqual(3);
expect(scheduler.counter).toEqual(3);

//Wait internal counter expiration
await wait(1000);
expect(scheduler.counter).toEqual(0);
scheduler.setTimeout(action);
await wait(500);
expect(counter).toEqual(4);
expect(scheduler.counter).toEqual(1);
});
});

0 comments on commit 21efdb8

Please sign in to comment.