Polling vs Event-Driven Detection
What you'll learn: How to choose between periodically checking connectivity versus listening for network state changes.
When monitoring network connectivity, you have two fundamental approaches: polling (repeatedly checking at intervals) and event-driven detection (listening for change events). Each has distinct tradeoffs.
Polling: Active Checking
Polling means repeatedly sending test requests or checking navigator.onLine at fixed intervals (every 5 seconds, 30 seconds, etc.). Think of it like constantly asking "Are we still connected?" on a schedule.
Pros:
- Detects actual connectivity to your server (not just the device's network interface)
- Catches gradual degradation or intermittent issues
- Works when events fail to fire
Cons:
- Battery drain on mobile devices from constant activity
- Wasted bandwidth and server resources
- May miss very brief disconnections between checks
Event-Driven: Reactive Listening
Event-driven detection uses the online and offline events fired by the browser when network state changes. It's like having an alarm that only rings when something changes.
Pros:
- Instant notification when state changes
- Zero overhead when nothing changes
- Battery-friendly and efficient
Cons:
- Only detects interface-level changes (not server reachability)
- Events may not fire reliably on all browsers/platforms
- Misses "zombie" connections (appears online but actually broken)
Hybrid Approach
For robust applications, combine both: use events for immediate response, then trigger active connectivity checks only when needed. This gives you the efficiency of events with the reliability of polling.
Key Takeaway: Event-driven detection is efficient for immediate state changes, polling catches real connectivity issues, and a hybrid approach balances battery life with reliability for production applications.