uppy/packages/@uppy/utils/src/ProgressTimeout.ts
Antoine du Hamel 51ecc66e64
@uppy/utils: refactor to TS (#4699)
Co-authored-by: Mikael Finstad <finstaden@gmail.com>
Co-authored-by: Nick Rutten <2504906+nickrttn@users.noreply.github.com>
Co-authored-by: Murderlon <merlijn@soverin.net>
Co-authored-by: Artur Paikin <artur@arturpaikin.com>
2023-11-06 15:01:50 +01:00

45 lines
1.1 KiB
TypeScript

/**
* 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,
timeoutHandler: Parameters<typeof setTimeout>[0],
) {
this.#timeout = timeout
this.#onTimedOut = timeoutHandler
}
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