aboutsummaryrefslogtreecommitdiff
path: root/e2e/eventually.ts
blob: 12c4552eab1f2a1171a0cb55c7eefbd3951b072f (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> => {
  let start = Date.now();
  let loop = async() => {
    try {
      await fn();
    } catch (err) {
      if (Date.now() - start > timeout) {
        throw err;
      }
      await sleep(interval);
      await loop();
    }
  };
  await loop();
};

export default eventually;