ProgressTimeout.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. */
  7. class ProgressTimeout {
  8. #aliveTimer
  9. #isDone = false
  10. #onTimedOut
  11. #timeout
  12. constructor (timeout, timeoutHandler) {
  13. this.#timeout = timeout
  14. this.#onTimedOut = timeoutHandler
  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. if (this.#timeout > 0) {
  22. clearTimeout(this.#aliveTimer)
  23. this.#aliveTimer = setTimeout(this.#onTimedOut, this.#timeout)
  24. }
  25. }
  26. done () {
  27. if (!this.#isDone) {
  28. clearTimeout(this.#aliveTimer)
  29. this.#aliveTimer = null
  30. this.#isDone = true
  31. }
  32. }
  33. }
  34. export default ProgressTimeout