forked from clerk/javascript
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoller.ts
43 lines (34 loc) · 939 Bytes
/
poller.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
import { createWorkerTimers } from './workerTimers';
export type PollerStop = () => void;
export type PollerCallback = (stop: PollerStop) => Promise<unknown>;
export type PollerRun = (cb: PollerCallback) => Promise<void>;
type PollerOptions = {
delayInMs: number;
};
export type Poller = {
run: PollerRun;
stop: PollerStop;
};
export function Poller({ delayInMs }: PollerOptions = { delayInMs: 1000 }): Poller {
const workerTimers = createWorkerTimers();
let timerId: number | undefined;
let stopped = false;
const stop: PollerStop = () => {
if (timerId) {
workerTimers.clearTimeout(timerId);
workerTimers.cleanup();
}
stopped = true;
};
const run: PollerRun = async cb => {
stopped = false;
await cb(stop);
if (stopped) {
return;
}
timerId = workerTimers.setTimeout(() => {
void run(cb);
}, delayInMs) as any as number;
};
return { run, stop };
}