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();
    /*$.ajax(url: urlToBeCalled);*/
}, 5000);

window.addEventListener("offline", function(e) { console.log("offline"); clearInterval(timing);});

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?

  • \$\begingroup\$ HTML5 Push API, I guess. \$\endgroup\$ – 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

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.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.