pleroma-fe/src/services/promise_interval/promise_interval.js

42 lines
1 KiB
JavaScript
Raw Normal View History

2020-09-04 11:19:53 +03:00
// 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.
2020-09-02 21:08:06 +03:00
2026-06-16 17:06:17 +03:00
const wait = (timeout) => {
let timeoutId
2026-06-16 17:32:26 +03:00
const promise = () =>
new Promise((resolve) => {
timeoutId = window.setTimeout(() => resolve(), timeout)
})
2026-06-16 17:06:17 +03:00
return { timeoutId, promise }
}
2020-09-04 11:19:53 +03:00
export const promiseInterval = (promiseCall, interval) => {
let stopped = false
let timeout = null
const stopFetcher = () => {
stopped = true
2020-09-02 21:01:31 +03:00
window.clearTimeout(timeout)
}
2026-06-16 17:06:17 +03:00
const loop = new Promise(async (resolve, reject) => {
try {
while (!stopped) {
await promiseCall()
const { timeoutId, promise } = wait(interval)
timeout = timeoutId
await promise()
}
resolve()
} catch (e) {
reject(e)
}
})
loop.then()
2020-09-04 11:19:53 +03:00
return { stop: stopFetcher }
}