-
-
Save desoga10/4639cca7cd2f052602a84ecfa1174b9f to your computer and use it in GitHub Desktop.
Online / Offline Status Detection w/ Async & Await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ********** Online / Offline Detection ********** */ | |
// Request a small image at an interval to determine status | |
// ** Get a 1x1 pixel image here: http://www.1x1px.me/ | |
// ** Use this code with an HTML element with id="status" | |
const checkOnlineStatus = async () => { | |
try { | |
const online = await fetch("/1pixel.png"); | |
return online.status >= 200 && online.status < 300; // either true or false | |
} catch (err) { | |
return false; // definitely offline | |
} | |
}; | |
setInterval(async () => { | |
const result = await checkOnlineStatus(); | |
const statusDisplay = document.getElementById("status"); | |
statusDisplay.textContent = result ? "Online" : "OFFline"; | |
}, 3000); // probably too often, try 30000 for every 30 seconds | |
// forgot to include async load event listener in the video! | |
window.addEventListener("load", async (event) => { | |
const statusDisplay = document.getElementById("status"); | |
statusDisplay.textContent = (await checkOnlineStatus()) | |
? "Online" | |
: "OFFline"; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment