setTimeout but for a given time

11,975

Solution 1

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.

Solution 2

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.

Solution 3

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!

Solution 4

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

const myDate = new Date('...');
setTimeout(func, myDate - Date.now());
Share:
11,975
Deniz Dogan
Author by

Deniz Dogan

Updated on June 07, 2022

Comments

  • Deniz Dogan
    Deniz Dogan almost 2 years

    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.