aboutsummaryrefslogtreecommitdiff
path: root/src/services/promise_interval/promise_interval.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/services/promise_interval/promise_interval.js')
-rw-r--r--src/services/promise_interval/promise_interval.js34
1 files changed, 34 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..0c0a66a0
--- /dev/null
+++ b/src/services/promise_interval/promise_interval.js
@@ -0,0 +1,34 @@
+
+// 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
+
+ const func = () => {
+ const promise = promiseCall()
+ // something unexpected happened and promiseCall did not
+ // return a promise, abort the loop.
+ if (!(promise && promise.finally)) {
+ console.warn('promiseInterval: promise call did not return a promise, stopping interval.')
+ return
+ }
+ promise.finally(() => {
+ if (stopped) return
+ timeout = window.setTimeout(func, interval)
+ })
+ }
+
+ const stopFetcher = () => {
+ stopped = true
+ window.clearTimeout(timeout)
+ }
+
+ timeout = window.setTimeout(func, interval)
+
+ return { stop: stopFetcher }
+}