blob: 9d21022b75821b9bedef2a09e2ab9c9422475529 (
plain) (
blame)
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
|
const defaultInterval = 100;
const defaultTimeout = 2000;
type Handler = () => void;
const sleep = (ms: number): Promise<void> => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
const eventually = async (
fn: Handler,
timeout = defaultTimeout,
interval = defaultInterval
): Promise<void> => {
const start = Date.now();
const loop = async () => {
try {
await fn();
} catch (err) {
if (Date.now() - start > timeout) {
throw err;
}
await sleep(interval);
await loop();
}
};
await loop();
};
export default eventually;
|