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?