8

I want to trigger a javascript function when the time reaches, say, 3:00 PM.

The time will be assigned dynamically. So is there any javascript function to achieve that??

ptamzz
  • 9,235
  • 31
  • 91
  • 147
  • You want to trigger it exactly at 3:00pm, or check at specific intervals if 3:00pm has been passed? – Andy E Jan 31 '11 at 18:52
  • Say like I want to trigger the function at exactly 3:00PM everyday.. something like an alarm. (Although, the time will be assigned dynamically later on) – ptamzz Jan 31 '11 at 18:58

1 Answers1

9

You just need to calculate the difference between the current time and the target time and use setTimeout() with that value.

For example, depending on how your target browsers parse dates, you could do the following:

function alert3pm() {
  alert("It's 3PM!");
}
var timeAt3pm = new Date("1/31/2011 03:00:00 PM").getTime()
  , timeNow = new Date().getTime()
  , offsetMillis = timeAt3pm - timeNow;
setTimeout(alert3pm, offsetMillis);

Or rather, instead of parsing a date (since that's really inconsistent between browsers) you could do something like this:

function getTimeAtHour(hour) {
  var t = new Date();
  t.setHours(hour);
  t.setMinutes(0);
  t.setSeconds(0);
  t.setMilliseconds(0);
  return t;
}
michael_bitard
  • 3,613
  • 1
  • 24
  • 35
maerics
  • 151,642
  • 46
  • 269
  • 291
  • No difference calculation needed for this one, there's no time period involved. – Andy E Jan 31 '11 at 18:53
  • 1
    Sure there is, setTimeout takes a time period to wait (in ms) and that time period should be the difference between now and the "alarm" time. – maerics Jan 31 '11 at 19:01
  • 1
    Unusual syntax for declaring a function - perhaps for example purposes, using the more standard `function alert3pm(){}` might be clearer? – Basic Jan 31 '11 at 19:04
  • 1
    @Basiclife: A JavaScript user should rather be familiar with both... and I'm not sure if either of them qualifies as "more standard" nowadays. – Matti Virkkunen Jan 31 '11 at 19:59
  • @Matti Virkkunen I understand that both are equally valid but since the OP isn't aware of how to use `SetTimeout()` to wait until a specified time, it's unlikely he's familiar with alternate techniques for defining functions. I wasn't trying to start a syntax war but I do believe that most JS tutorials tend to use the `function Name(){}` syntax as it's closer to the implementation used in other languages. I was simply trying to make the answer easier to understand for the OP. I'm sorry if you don't agree. – Basic Jan 31 '11 at 21:01