Repository navigation
Expand file tree
/
Copy pathshared-timers.tsx
More file actions
103 lines (89 loc) · 2.41 KB
/
Copy pathshared-timers.tsx
File metadata and controls
103 lines (89 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import {printOutstandingTimerListeners} from '@/local-debug'
import logger from '@/logger'
/**
* Shared timers for when disparate components need to
* be kept in sync. Timers are given a key that can be
* subscribed to. When all observers of a timer are
* removed the timeout is cancelled and the key deleted
*/
export type SharedTimerID = number
// Global ID for refs to timers
let id: SharedTimerID = 0
type Ref = {
fn: () => void
id: SharedTimerID
}
type RefMap = {[K in string]: Array<Ref>}
type Timer = {
key: string
timeoutID: ReturnType<typeof setInterval>
}
class Timers {
_refs: RefMap = {}
_timers: Array<Timer> = []
constructor(debug: boolean) {
if (debug) {
setInterval(() => {
if (Object.keys(this._refs).length) {
logger.localLog('Outstanding shared timer listener debugger:', this._refs)
}
}, 10000)
}
}
addObserver = (
fn: () => void,
{
key,
ms,
}: {
key: string
ms?: number
}
): SharedTimerID => {
id++
const ref = {fn, id}
if (this._refs[key]) {
this._refs[key]!.push(ref)
return id
} else if (!ms) {
const msg = `SharedTimers: Tried to add timer observer with key '${key}' but no timer exists`
logger.error(msg)
throw new Error(`SharedTimers: Tried to add timer observer with key '${key}' but no timer exists`)
}
this._refs[key] = [ref]
const timeoutID = setTimeout(() => this._handleTrigger(key), ms)
this._timers.push({key, timeoutID})
return id
}
removeObserver = (key: string, id: SharedTimerID) => {
if (this._refs[key]) {
const i = this._refs[key]!.findIndex(r => r.id === id)
if (i >= 0) {
this._refs[key]!.splice(i, 1)
if (!this._refs[key]!.length) {
delete this._refs[key] // eslint-disable-line
this._removeTimer(key)
}
}
}
}
_removeTimer = (key: string) => {
const i = this._timers.findIndex(t => t.key === key)
if (i > 0) {
clearTimeout(this._timers[i]?.timeoutID)
this._timers.splice(i, 1)
}
}
_handleTrigger = (key: string) => {
if (!this._refs[key]) {
// nobody's listening
return
}
const refs = this._refs[key]!
refs.forEach(r => r.fn())
delete this._refs[key] // eslint-disable-line
this._removeTimer(key)
}
}
const sharedTimer = new Timers(printOutstandingTimerListeners)
export default sharedTimer