Path: blob/main/components/gitpod-protocol/src/util/repeat.ts
2500 views
/**1* Copyright (c) 2021 Gitpod GmbH. All rights reserved.2* Licensed under the GNU Affero General Public License (AGPL).3* See License.AGPL.txt in the project root for license information.4*/56import { Disposable } from "..";7import { log } from "./logging";89/**10* This intends to be a drop-in replacement for 'setInterval' implemented with a 'setTimeout' chain11* to ensure we're not creating more timeouts than we can process.12* @param op13* @param everyMilliseconds14* @returns15*/16export function repeat(op: () => Promise<void> | void, everyMilliseconds: number): Disposable {17let timer: NodeJS.Timeout | undefined = undefined;18let stopped = false;19const repeated = () => {20if (stopped) {21// in case we missed the clearTimeout i 'await'22return;23}2425timer = setTimeout(async () => {26try {27await op();28} catch (err) {29// catch error here to30log.error(err);31}3233repeated(); // chain ourselves - after the 'await'34}, everyMilliseconds);35};36repeated();3738return Disposable.create(() => {39stopped = true;40if (timer) {41clearTimeout(timer);42}43});44}454647