Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

waitForOnline

Waits until the browser goes online.

TypeScript
Copied!
1/**
2 * Waits until the browser goes online.
3 *
4 * @returns A Promise that resolves when the device regains internet access.
5 */
6export function waitForOnline(): Promise<void> {
7  if (typeof window === 'undefined') {
8    return Promise.reject(new Error('waitForOnline can only be used in the browser'));
9  }
10
11  if (navigator.onLine) {
12    return Promise.resolve();
13  }
14
15  return new Promise(resolve => {
16    const onOnline = () => {
17      window.removeEventListener('online', onOnline);
18      resolve();
19    };
20    window.addEventListener('online', onOnline);
21  });
22}
  • Promise-Based Simplicity

    Uses a clean, promise-based interface that's easy to integrate with async workflows.

  • Automatic Cleanup

    Removes the event listener once the device comes online, preventing memory leaks.

  • Immediate Resolution if Already Online

    Avoids unnecessary waiting by resolving immediately if the device is already online.

  • Environment Safety Check

    Provides a clear error if called in a non-browser environment, improving reliability.

Tests | Examples

TypeScript
Copied!
1test('waitForOnline - resolves immediately if already online', async () => {
2  Object.defineProperty(navigator, 'onLine', {
3    configurable: true,
4    get: () => true,
5  });
6
7  await expect(waitForOnline()).resolves.toBeUndefined();
8});
9
10test('waitForOnline - resolves after online event if initially offline', async () => {
11  Object.defineProperty(navigator, 'onLine', {
12    configurable: true,
13    get: () => false,
14  });
15
16  const promise = waitForOnline();
17
18  // Simulate going online
19  window.dispatchEvent(new Event('online'));
20
21  await expect(promise).resolves.toBeUndefined();
22});
23
24test('waitForOnline - rejects outside the browser', async () => {
25  const originalWindow = globalThis.window;
26  // @ts-ignore
27  delete globalThis.window;
28
29  await expect(waitForOnline()).rejects.toThrow(
30    'waitForOnline can only be used in the browser'
31  );
32
33  globalThis.window = originalWindow;
34});

Common Use Cases

  • Deferred API Requests

    Wait to retry failed requests only after internet connectivity is restored.

  • Progressive Web App Recovery

    Resume background sync or updates after the user reconnects.

  • UI State Restoration

    Restore disabled or blocked UI actions (like save buttons) when online.

  • Error Notification Suppression

    Delay error prompts or retries until connectivity is regained.

Codebase: Utilities -> Network -> waitForOnline | Yevhen Klymentiev