setTimeout but for a given time

You have to compute the number of milliseconds between now and your date object:

function setToHappen(fn, date){
    return setTimeout(fn, date - Date.now());
}

NB Please note @calvin's answer: this will not work if the number of milliseconds is greater than 2147483647.


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;
  return setTimeout(fn, diff);
 }

EDIT: removed the extra multiplication by 1000, thanks chris for pointing that out!


Since people are talking about calculating timeout intervals using date objects, it should be noted that 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.


You can simply subtract Date.now() from the date

const myDate = new Date('...');
setTimeout(func, myDate - Date.now());