-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoll.ts
45 lines (36 loc) · 1.1 KB
/
poll.ts
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import type { ErrorType } from '../errors/utils.js'
import { wait } from './wait.js'
type PollOptions<TData> = {
// Whether or not to emit when the polling starts.
emitOnBegin?: boolean | undefined
// The initial wait time (in ms) before polling.
initialWaitTime?: ((data: TData | void) => Promise<number>) | undefined
// The interval (in ms).
interval: number
}
export type PollErrorType = ErrorType
/**
* @description Polls a function at a specified interval.
*/
export function poll<TData>(
fn: ({ unpoll }: { unpoll: () => void }) => Promise<TData | void>,
{ emitOnBegin, initialWaitTime, interval }: PollOptions<TData>,
) {
let active = true
const unwatch = () => (active = false)
const watch = async () => {
let data: TData | void = undefined
if (emitOnBegin) data = await fn({ unpoll: unwatch })
const initialWait = (await initialWaitTime?.(data)) ?? interval
await wait(initialWait)
const poll = async () => {
if (!active) return
await fn({ unpoll: unwatch })
await wait(interval)
poll()
}
poll()
}
watch()
return unwatch
}