Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/gitpod-protocol/src/util/repeat.ts
2500 views
1
/**
2
* Copyright (c) 2021 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { Disposable } from "..";
8
import { log } from "./logging";
9
10
/**
11
* This intends to be a drop-in replacement for 'setInterval' implemented with a 'setTimeout' chain
12
* to ensure we're not creating more timeouts than we can process.
13
* @param op
14
* @param everyMilliseconds
15
* @returns
16
*/
17
export function repeat(op: () => Promise<void> | void, everyMilliseconds: number): Disposable {
18
let timer: NodeJS.Timeout | undefined = undefined;
19
let stopped = false;
20
const repeated = () => {
21
if (stopped) {
22
// in case we missed the clearTimeout i 'await'
23
return;
24
}
25
26
timer = setTimeout(async () => {
27
try {
28
await op();
29
} catch (err) {
30
// catch error here to
31
log.error(err);
32
}
33
34
repeated(); // chain ourselves - after the 'await'
35
}, everyMilliseconds);
36
};
37
repeated();
38
39
return Disposable.create(() => {
40
stopped = true;
41
if (timer) {
42
clearTimeout(timer);
43
}
44
});
45
}
46
47