diff options
| author | Shpuld Shpuldson <shp@cock.li> | 2020-09-04 11:19:53 +0300 |
|---|---|---|
| committer | Shpuld Shpuldson <shp@cock.li> | 2020-09-04 11:19:53 +0300 |
| commit | 3fb35e8123d3a8cd151571b315b7ec4d7e0875c7 (patch) | |
| tree | e473ffedfea68b8a3a5f661182e2e23928877510 /src/services/promise_interval/promise_interval.js | |
| parent | 5b403ba7d13eaf851ae43e814c583ceb018e2d20 (diff) | |
rename to promiseInterval
Diffstat (limited to 'src/services/promise_interval/promise_interval.js')
| -rw-r--r-- | src/services/promise_interval/promise_interval.js | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/services/promise_interval/promise_interval.js b/src/services/promise_interval/promise_interval.js new file mode 100644 index 00000000..ee46a236 --- /dev/null +++ b/src/services/promise_interval/promise_interval.js @@ -0,0 +1,28 @@ + +// promiseInterval - replacement for setInterval for promises, starts counting +// the interval only after a promise is done instead of immediately. +// - promiseCall is a function that returns a promise, it's called the first +// time after the first interval. +// - interval is the interval delay in ms. + +export const promiseInterval = (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) + } + + timeout = window.setTimeout(func, interval) + + return { stop: stopFetcher } +} |
