1.5 KB59 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8import type {Disposable} from './types';
9
10export class Timer implements Disposable {
11 private timerId: null | number = null;
12 private disposed = false;
13 private callback: () => void;
14
15 /**
16 * The `callback` can return `false` to auto-stop the timer.
17 * The timer auto stops if being GC-ed.
18 */
19 constructor(
20 callback: () => void | boolean,
21 public intervalMs = 1000,
22 enabled = false,
23 ) {
24 const thisRef = new WeakRef(this);
25 this.callback = () => {
26 const timer = thisRef.deref();
27 if (timer == null) {
28 // The "timer" object is GC-ed. Do not run this interval.
29 return;
30 }
31 // Run the callback and schedules the next interval.
32 timer.timerId = null;
33 const shouldContinue = callback();
34 if (shouldContinue !== false) {
35 timer.enabled = true;
36 }
37 };
38 this.enabled = enabled;
39 }
40
41 set enabled(value: boolean) {
42 if (value && this.timerId === null && !this.disposed) {
43 this.timerId = window.setTimeout(this.callback, this.intervalMs);
44 } else if (!value && this.timerId !== null) {
45 window.clearTimeout(this.timerId);
46 this.timerId = null;
47 }
48 }
49
50 get enabled(): boolean {
51 return this.timerId !== null;
52 }
53
54 dispose(): void {
55 this.enabled = false;
56 this.disposed = true;
57 }
58}
59