signal-desktop/ts/util/waitForOnline.ts

41 lines
975 B
TypeScript
Raw Normal View History

2021-04-08 16:24:21 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
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);
2021-11-01 18:38:26 +00:00
if (typeof timeoutId === 'number') {
clearTimeout(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
});
}