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.
Clever.
The following example forces a page reload just before midnight:
//the window reload function. you could of course do anything here function forceMidnightPageReload() { window.location.reload(true); } //helper function to build up the desire time trigger function forceMidnightPageReloadGetTargetTime(hour,minute) { var t = new Date(); t.setHours(hour); t.setMinutes(minute); t.setSeconds(0); t.setMilliseconds(0); 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); }
Useful.