UNPKG

1.09 kBJavaScriptView Raw
1/**
2 * Helper to abort upload requests if there has not been any progress for `timeout` ms.
3 * Create an instance using `timer = new ProgressTimeout(10000, onTimeout)`
4 * Call `timer.progress()` to signal that there has been progress of any kind.
5 * Call `timer.done()` when the upload has completed.
6 */
7class ProgressTimeout {
8 constructor (timeout, timeoutHandler) {
9 this._timeout = timeout
10 this._onTimedOut = timeoutHandler
11 this._isDone = false
12 this._aliveTimer = null
13 this._onTimedOut = this._onTimedOut.bind(this)
14 }
15
16 progress () {
17 // Some browsers fire another progress event when the upload is
18 // cancelled, so we have to ignore progress after the timer was
19 // told to stop.
20 if (this._isDone) return
21
22 if (this._timeout > 0) {
23 if (this._aliveTimer) clearTimeout(this._aliveTimer)
24 this._aliveTimer = setTimeout(this._onTimedOut, this._timeout)
25 }
26 }
27
28 done () {
29 if (this._aliveTimer) {
30 clearTimeout(this._aliveTimer)
31 this._aliveTimer = null
32 }
33 this._isDone = true
34 }
35}
36
37module.exports = ProgressTimeout