I am creating a tizen web app where I am checking the internet connection and the do a fetch request to check that the internet is working. but the issue is that it randomly tells me that no internet is available and the API request is not fulfilled. to prevent the request from taking unlimited time I used a setTimeout.
I use the same function in WebOS LG TV and it works perfactly fine. the device I have is Samsung 43in 5 series T5300 HD TV
I am using this function to detect wifi and internet connection. in randomUrl I am using a google, github and other populer urls.
let failureCount = 0;
function checkInternetConnection() {
// first check if the wifi is connected
const isOnline = navigator.onLine;
if (!isOnline) {
console.log("Internet check failed:", "no wifi");
isPopupShown = true;
return;
}
const randomUrl = randomUrls[Math.floor(Math.random() * randomUrls.length)];
// Create a promise that rejects after 3 seconds to simulate a timeout.
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timeout error")), 3000)
);
// Use Promise.race to either get the fetch result or timeout.
Promise.race([
fetch(randomUrl, { method: "GET", cache: "no-cache" }),
timeoutPromise
])
.then(() => {
console.log("Internet is available");
failureCount = 0;
if (isPopupShown) {
isPopupShown = false;
}
})
.catch((error) => {
console.log("Internet check failed:", error.message);
failureCount = failureCount + 1;
console.log("Failure count:", failureCount);
// Only show the popup after 3 consecutive failures.
if (failureCount >= 3 && !isPopupShown) {
isPopupShown = true;
}
});
}