I believe currently, that is the most effective way to tell if you're connected.
If you'd like to have an "event-based" solution, you can wrap the polling service with something like this:
connectivity-checker.js
const isOnline = require("is-online");
function ConnectivityChecker (callback, interval) {
this.status = false;
this.callback = callback;
this.interval = this.interval;
// Determines if the check should check on the next interval
this.shouldCheckOnNextInterval = true;
}
ConnectivityChecker.prototype.init = function () {
this.cleanUp();
this.timer = setInterval(function () {
if (this.shouldCheck) {
isOnline().then(function (status) {
if (this.status !== status) {
this.status = status;
this.callback(status);
this.shouldCheckOnNextInterval = true;
}
}).catch(err => {
console.error(err);
this.shouldCheckOnNextInterval = true;
})
// Disable 'shouldCheckOnNextInterval' if current check has not resolved within the interval time
this.shouldCheckOnNextInterval = false;
}
}, this.interval);
}
ConnectivityChecker.prototype.cleanUp = function () {
if (this.timer) clearInterval(this.timer);
}
export { ConnectivityChecker };
Then in your site of usage (E.g. app.js
)
app.js
const { ConnectivityChecker } = require("/path/to/connectivity-checker.js");
const checker = new ConnectivityChecker(function(isOnline) {
// Will be called ONLY IF isOnline changes from 'false' to 'true' or from 'true' to 'false'.
// Will be not called anytime isOnline status remains the same from between each check
// This simulates the event-based nature you're looking for
if (isOnline) {
// Do stuff if online
} else {
// Do stuff if offline
}
}, 5000);
// Where your app starts, call
checker.init();
// Where your app ends, call
// checker.cleanUp();
Hope this helps...