-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ProgressTimeout.ts
46 lines (38 loc) · 1.19 KB
/
ProgressTimeout.ts
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
/**
* Helper to abort upload requests if there has not been any progress for `timeout` ms.
* Create an instance using `timer = new ProgressTimeout(10000, onTimeout)`
* Call `timer.progress()` to signal that there has been progress of any kind.
* Call `timer.done()` when the upload has completed.
*/
class ProgressTimeout {
#aliveTimer?: ReturnType<typeof setTimeout>
#isDone = false
#onTimedOut: Parameters<typeof setTimeout>[0]
#timeout: number
constructor(
timeout: number,
// eslint-disable-next-line no-shadow
timeoutHandler: (timeout: number) => void,
) {
this.#timeout = timeout
this.#onTimedOut = () => timeoutHandler(timeout)
}
progress(): void {
// Some browsers fire another progress event when the upload is
// cancelled, so we have to ignore progress after the timer was
// told to stop.
if (this.#isDone) return
if (this.#timeout > 0) {
clearTimeout(this.#aliveTimer)
this.#aliveTimer = setTimeout(this.#onTimedOut, this.#timeout)
}
}
done(): void {
if (!this.#isDone) {
clearTimeout(this.#aliveTimer)
this.#aliveTimer = undefined
this.#isDone = true
}
}
}
export default ProgressTimeout