Setting and clearing JavaScript intervals depending on browser state

I'm trying to build an application which automatically refreshes the page with fresh stuff from the server. I was trying out the approach with something basic like printing out the time, to test out my approach. I go to the page, and it starts printing the time every 5 seconds in the console. When I switch to offline mode, the auto-printing should stop, and when I come back to online mode, the auto-printing should resume again. So far, I have this:

timing = setInterval(function() {
urlToBeCalled = '/autoupdate/';
var d = new Date();
console.log(d.toLocaleTimeString());
/*\$.ajax(url: urlToBeCalled);*/
}, 5000);

window.addEventListener("online", function(e) { console.log("online"); timing = setInterval(function() {.... blah... blah... blah...}, 5000)


(The "blah"s are the same code from the timing variable above)

It works, but I don't think this is a very proper way to do things. Is there any better way to accomplish this?

• HTML5 Push API, I guess. – wOxxOm Sep 10 '16 at 10:01

I can think about two ways of doing this.

Using server

You can make your browser work as a 'listener' from the server using the Push API, its probably the best way, but sometimes you will not have access to make changes in the server.

Using client

Create a run loop.

var interval;
var hasBeenOffline = true;
var loop = function() {
// this will be to function that will run every X seconds
if(online) {
// if the server are online
if (hasBeenOffline) {
interval = setInterval(function() { /* code */ } )
}
} else {
// server offline
clearInterval(interval)
}
};

setInterval(loop, 1000);


In this way you will have the a better control of the application flow, and will not be required to create the same interval twice in your code.

Some frameworks use a similiar approach, read about the Ember Run Loop to know more about the concept.