forked from WorldBrain/Memex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpausable-timer.js
57 lines (48 loc) · 1.31 KB
/
pausable-timer.js
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
class PausableTimer {
_timeoutId
/**
* @param {Object} args
* @param {() => any} args.cb The callback to delay.
* @param {number} args.delay Time in ms to delay for.
* @param {boolean} [args.start=true] Whether or not to start the timeout immediately or on later `.resume()` call.
*/
constructor({ cb, delay, start = true }) {
this.cb = cb
this._remain = delay
if (start) {
this.resume()
}
}
set delay(val) {
this._remain = val
}
/**
* Resumes a paused timer, storing the resumed time and new timer ID as state.
*/
resume() {
if (this._remain <= 0) {
return
}
this._start = Date.now()
clearTimeout(this._timeoutId)
this._timeoutId = setTimeout(this.cb, this._remain)
}
/**
* Pauses the timer and stores the remaining state for next `.resume()` invocation.
*/
pause() {
if (this._remain <= 0 || this._start == null) {
return
}
clearTimeout(this._timeoutId)
this._remain -= Date.now() - this._start
}
/**
* Clears any ongoing timer and removes it from state.
*/
clear() {
clearTimeout(this._timeoutId)
this._timeoutId = null
}
}
export default PausableTimer