JavaScript page refresh timer

I wanted a web page I’ve been working on to auto-refresh, but not just after a certain time has elapsed, but when the clock is just past a quarter hour interval (i.e. x:15, x:30, x:45, x:00).

It’s pretty straightforward, but as I was searching around, it seems to be a pretty common question, so figured I’d put up my own answer here:

 function setAutoRefresh()
 {
   var interval = 15*60*1000; //every 15 mins...
   var timeNow = new Date().getTime();
   var nextInterval = (Math.floor(timeNow/interval)+1) * interval + 10000; //next time interval, plus 10 seconds...
   var nextIntDate = new Date();
   nextIntDate.setTime(nextInterval);
   console.log("Next timeout tick: " + nextIntDate.toLocaleTimeString());
   autoRefreshTimer = setTimeout(function(){
   console.log("Auto-refresh: " + new Date().toLocaleTimeString());
   reloadPage();
   },nextInterval - new Date().getTime());
 }

So we round up the current time in ms to the next 15 min interval, and add 10,000 so our event triggers 10 seconds after the interval (I have another process that ticks every 5 mins and updates the DB table this web page pulls from, so I wanted to make sure I got the latest data).

The var autoRefreshTimer is global and can be used to cancel the timeout timer when the page becomes hidden.

The var nextIntDate is only used for the console log, and can be removed if you don’t need that.

The function reloadPage resends all my ajax calls to reload the different data on the web page and then calls setAutoRefresh when it’s all done.

Hope that all makes sense.

 

Leave a Reply