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