views:

334

answers:

3

Is there anything readily available in JavaScript (i.e. not through "plugins") that allows me to do something like setTimeout, but instead of saying in how many milliseconds something should happen, I give it a date object telling it when to do something?

setToHappen(function () {
    alert('Wake up!');
}, new Date("..."));

And yes, I know I can do this by simply subtracting new Date() with my existing date object (or maybe it's the other way around) to get the amount of milliseconds, but I'd still like to know.

+3  A: 

No, but you could easily write your own function. Just calculate the diference between now and the given moment in miliseconds and call setTimeout with that.

Something like this:

 setToHappen = function(fn, date){
  var now = new Date().getTime();
  var diff = date.getTime() - now;
  var milliseconds = diff * 1000;
  return setTimeout(fn, milliseconds);
 }
Pim Jager
+5  A: 

You'd have to just find the number of milliseconds between now and your date object.

function setToHappen(fn, d){
    var t = d.getTime() - (new Date()).getTime();
    return setTimeout(fn, t);
}
Simon
don't you have to multiply by 1000 to get the miliseconds?
Pim Jager
@Pim, no you don't. 'getTime()' returns the number of milliseconds between 00:00:00 1/1/1970 and the corresponding date object.
J-P
AH ok, I thought it was in seconds.
Pim Jager
+2  A: 

Since people are talking about calculating timeout intervals using date objects, it should be noted that, in Firefox, the max value setTimeout() will accept for the interval parameter is 2147483647 (2^31 - 1) as PRIntervalTime is a signed 32-bit integer. That comes out to just under 25 days.

Calvin