aboutsummaryrefslogtreecommitdiff
path: root/src/services/fetcher/fetcher.js
blob: 5a6ed4b8e1c6154572e56dad64e1bb359ea48bc6 (plain)
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

// makeFetcher - replacement for setInterval for fetching, starts counting
// the interval only after a request is done instead of immediately.
// promiseCall is a function that returns a promise, it's called when created
// and after every interval.
// interval is the interval delay in ms.

export const makeFetcher = (promiseCall, interval) => {
  let stopped = false
  let timeout = null
  let func = () => {}

  func = () => {
    promiseCall().finally(() => {
      if (stopped) return
      timeout = window.setTimeout(func, interval)
    })
  }

  const stopFetcher = () => {
    stopped = true
    window.clearTimeout(timeout)
  }

  func()

  return stopFetcher
}