Dimitri Vorontzov
Dimitri Vorontzov

Reputation: 8104

Testing Internet connection at regular intervals

I want to check if a certain website is online every 3 seconds.

If the connection exists and the site is online, I want to show "Connected" alert every 3 seconds, but if there's no connection or the site is not online, I want to show "Not connected" alert, also every 3 seconds.

I tried this:

var myURL = "http://www.example.com/";

function testConnection(url) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() { alert("Connected!");}   
    xmlhttp.onerror = function() { alert("Not Connected"); }
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}

var tickingClock = setInterval(testConnection(myURL), 3000);

This, however, results in an alert only appearing once. What should I change in this snippet tp make it do what I want it to do?

Upvotes: 2

Views: 1166

Answers (1)

Joe Enos
Joe Enos

Reputation: 40403

You are calling the function, rather than putting a reference to the function in your setInterval statement. The proper method would be:

var tickingClock = setInterval(function() { testConnection(myURL); }, 3000);

setInterval accepts a function (or a string, but try to avoid using a string). Your code fires the testConnection method, then gives the return value as the argument to setInterval. But that return value is undefined, so the setInterval has nothing to do.

Upvotes: 5

Related Questions