Setting and clearing JavaScript intervals depending on browser state
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.