aboutsummaryrefslogtreecommitdiffstats
path: root/packages/utils/src/interval_utils.ts
blob: 6e296ceeb1832fc3c764e7646416ff3a9ee7f8d9 (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
31
32
33
34
35
36
37
38
39
40

export const intervalUtils = {
    setAsyncExcludingInterval(
        fn: () => Promise<void>,
        intervalMs: number,
        onError: (err: Error) => void,
    ): NodeJS.Timer {
        let isLocked = false;
        const intervalId = setInterval(async () => {
            if (isLocked) {
                return;
            } else {
                isLocked = true;
                try {
                    await fn();
                } catch (err) {
                    onError(err);
                }
                isLocked = false;
            }
        }, intervalMs);
        return intervalId;
    },
    clearAsyncExcludingInterval(intervalId: NodeJS.Timer): void {
        clearInterval(intervalId);
    },
    setInterval(fn: () => void, intervalMs: number, onError: (err: Error) => void): NodeJS.Timer {
        const intervalId = setInterval(() => {
            try {
                fn();
            } catch (err) {
                onError(err);
            }
        }, intervalMs);
        return intervalId;
    },
    clearInterval(intervalId: NodeJS.Timer): void {
        clearInterval(intervalId);
    },
};