The current solution is simple and elegant, but has one big drawback and that is that it doesn’t take poor connections into account.
Basically, as long as the initial online check succeeds, regardless of how long it takes to succeed, it is going to return “true” | “online”. Now this is technically correct (as explained previously, if you can connect you are technically connected|online), but not necessarily practical. This is especially true if all subsequent calls, which will most likely be more resource intensive than the original check, will also take a really long time to resolve.
Therefore, it may be a good idea to time the online check and have a threshold / benchmark duration that you can compare against, and only return “true” | “online” if the online check succeeds and succeeds in a timely manner.
Something like this:
function checkConnection() {
var threshold = 2000; // threshold in milliseconds
// The threshold is basically an indication of the max time you expect the call to OnlineDB.user.first() to take
// This will vary based on connection speed and strength
// Here are some basic examples, but your mileage can and will vary
// RESULTS:
// WiFi: ~ 130ms
// Strong 3G: ~ 550ms
// Slow 3G: ~ 2000ms
var before = new Date();
// The app will have to wait for this to execute and so will spin and wait until it completes or times out by itself
var attempt = attemptOnlineCall();
var duration = (new Date().getTime()) - before.getTime();
if (attempt && duration < threshold) {
// Connected, and connected fast enough
return true;
} else {
// Not connected, or connected too slowly
return false;
}
}
function attemptOnlineCall() {
try {
var user = OnlineDB.user.first();
return true
} catch (err) {
return false;
}
}