1
\$\begingroup\$

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("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?

asked Sep 9, 2016 at 11:03
\$\endgroup\$
1
  • \$\begingroup\$ HTML5 Push API, I guess. \$\endgroup\$ Commented Sep 10, 2016 at 10:01

1 Answer 1

1
\$\begingroup\$

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.

answered Sep 13, 2016 at 12:53
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.