Skip to content

Commit

Permalink
Fix TimeoutScheduler disposing
Browse files Browse the repository at this point in the history
  • Loading branch information
maxima-net committed Sep 6, 2022
1 parent 12c2b05 commit 6ba60f1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/core/timeoutScheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Disposable } from '../common';

export class TimeoutScheduler implements Disposable {
private counterExpirationWatcherId: ReturnType<typeof setTimeout> | undefined;
private actionWatcherId: ReturnType<typeof setTimeout> | undefined;
private actionWatchers = new Set<ReturnType<typeof setTimeout>>();
private _counter = 0;

constructor(
Expand All @@ -22,8 +22,7 @@ export class TimeoutScheduler implements Disposable {
if (this.counterExpirationWatcherId)
clearTimeout(this.counterExpirationWatcherId);

if (this.actionWatcherId)
clearTimeout(this.actionWatcherId);
this.actionWatchers.forEach(watcher => clearTimeout(watcher));
}

setTimeout(action: () => void) {
Expand All @@ -32,7 +31,13 @@ export class TimeoutScheduler implements Disposable {

const timeoutIndex = Math.min(this.counter, this.timeouts.length - 1);
const timeout = this.timeouts[timeoutIndex];
this.actionWatcherId = setTimeout(action, timeout);

const watcherId = setTimeout(() => {
this.actionWatchers.delete(watcherId);
clearTimeout(watcherId);
action();
}, timeout);
this.actionWatchers.add(watcherId);

this.counter++;
}
Expand Down
17 changes: 17 additions & 0 deletions tests/core/timeoutScheduler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import { TimeoutScheduler } from '../../src/core';
describe('TimeoutScheduler', () => {
let scheduler: TimeoutScheduler;

beforeEach(() => {
jest.useRealTimers();
});

afterEach(() => {
scheduler.dispose();
});
Expand Down Expand Up @@ -76,4 +80,17 @@ describe('TimeoutScheduler', () => {
expect(counter).toEqual(4);
expect(scheduler.counter).toEqual(1);
});

test('stops all scheduled tasks on dispose', () => {
jest.useFakeTimers();
const action = jest.fn();
scheduler = new TimeoutScheduler([10000, 10000]);

scheduler.setTimeout(action);
scheduler.setTimeout(action);
scheduler.setTimeout(action);
expect(jest.getTimerCount()).toBe(3);
scheduler.dispose();
expect(jest.getTimerCount()).toBe(0);
});
});

0 comments on commit 6ba60f1

Please sign in to comment.