JavaScript: How To Trigger at a Specific Time CodeUnit 23 JAN 2013

Sometimes you want your web page to do something at a specific time. For example, perhaps you want your page to force a reload at midnight, say if it is being used as a monitor screen and you want to reload it in order to reset browser memory usage.

Anyway, triggering at a specific time using JavaScript turns out to be a fairly simple task, thanks to the useful timing function, setTimeout.

The trick is simple enough. On page load, grab the current timestamp using the Date() object. Then create a new Date() object and manually set its hour and minutes to match the time you want your event to trigger. The difference between the two objects’ times expressed in milliseconds is then used to create a setTimeout event, which naturally will trigger when those milliseconds are up.


The following example forces a page reload just before midnight:

//the window reload function. you could of course do anything here
function forceMidnightPageReload() {

//helper function to build up the desire time trigger
function forceMidnightPageReloadGetTargetTime(hour,minute) {
  var t = new Date();
  return t;

//get your offset to wait value
var timetarget = forceMidnightPageReloadGetTargetTime(23,59).getTime();
var timenow =  new Date().getTime();
var offsetmilliseconds = timetarget - timenow;

//if it isn't midnight yet, set a timeout.
if (offsetmilliseconds >= 0){
setTimeout(function(){forceMidnightPageReload();}, offsetmilliseconds);


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.