signal-desktop/ts/util/waitForOnline.ts

41 lines
1,008 B
TypeScript
Raw Normal View History

// Copyright 2021-2022 Signal Messenger, LLC
2021-04-08 16:24:21 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
import { clearTimeoutIfNecessary } from './clearTimeoutIfNecessary';
2021-04-08 16:24:21 +00:00
export function waitForOnline(
navigator: Readonly<{ onLine: boolean }>,
onlineEventTarget: EventTarget,
options: Readonly<{ timeout?: number }> = {}
2021-04-08 16:24:21 +00:00
): Promise<void> {
const { timeout } = options;
return new Promise((resolve, reject) => {
2021-04-08 16:24:21 +00:00
if (navigator.onLine) {
resolve();
return;
}
2021-11-01 18:38:26 +00:00
let timeoutId: undefined | ReturnType<typeof setTimeout>;
2021-04-08 16:24:21 +00:00
const listener = () => {
cleanup();
2021-04-08 16:24:21 +00:00
resolve();
};
const cleanup = () => {
onlineEventTarget.removeEventListener('online', listener);
clearTimeoutIfNecessary(timeoutId);
};
2021-04-08 16:24:21 +00:00
onlineEventTarget.addEventListener('online', listener);
if (timeout !== undefined) {
2021-11-01 18:38:26 +00:00
timeoutId = setTimeout(() => {
cleanup();
reject(new Error('waitForOnline: did not come online in time'));
}, timeout);
}
2021-04-08 16:24:21 +00:00
});
}