your alert and check need to be in the same function, along with the timer id (perfectTiming) being global.
var perfectTiming = null;
function check_connection() {
var online = navigator.onLine;
if (online) {
alert("ONLINE!");
clearInterval(perfectTiming);
}
}
function timed_alert() {
perfectTiming = setInterval(check_connection,3000);
}
timed_alert();
if you are trying to test to see if the user has an active internet connection that is harder as there is no real way for the browser to check this. You could however test several different ip/urls to see if they are reachable
var testUrlIndex = 0;
var testurls = [
"http://www.google.com",
"http://www.cnn.com"
];
function testURL(url)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==0)
{
testUrlIndex++;
if( testUrlIndex<testurls.length ) {
testUrl(testurls[testUrlIndex]);
} else {
weAppearToBeOffline();
}
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function weAppearToBeOffline() {
//DO whatever you need to do if we are offline.
}
testUrl(testurls[0]); //start the check
This code will check 2 urls (just add more urls to testurls
if u want to check more), if it goes though all of them and cant reach them it will call the weAppearToBeOffline
function
Now this is only faulty in a couple ways, one mainly being that there is a situation where maybe the user is online but cant reach any of those urls but can reach others .