Hunt
Hunt

Reputation: 8435

fire a time after specific date and time in javascript

i want to fire an event on specific date and time in javascript. for example ,

if current date and time is 19-11-2015 10:00 AM , and i set a timer on 19-11-2015 10:30 AM then , it should fire after 30 minutes. here set timer date could be after two days also.

my current code is as follows.

setTimer :function(hr  , min){


            var d1 = new Date();
            var d2 = new Date();
            console.log("Time 1 "+d1.getTime());

            d2.setMinutes(d1.getMinutes() + min);
            d2.setHours(d1.getHours() + hr);


            console.log("Time 2 "+d2.getTime());
            setTimeout(function(){

                   alert("called"); 


                },d2.getTime());
            alert("Before " + d1.getDate() + " - "+d1.getMonth() + " - "+d1.getFullYear() + "<>"+d1.getHours()+ ":"+d1.getMinutes() 
                    + "\n" +
                "After  " + d2.getDate() + " - "+d2.getMonth() + " - "+d2.getFullYear() + "<>"+d2.getHours()+ ":"+d2.getMinutes() );


        },

i called it using setTimer(0,1); to fire a timer after one minute but its not getting fired.

Upvotes: 0

Views: 1420

Answers (2)

Dan Prince
Dan Prince

Reputation: 30009

Using setTimeout is not a reliable way to create timers.

You're much better off using setInterval and checking whether you've reached the correct time yet.

function setTimer(hours, minutes) {
  var now = Date.now();

  // work out the event time in ms
  var hoursInMs = hours * 60 * 60 * 1000,
      minutesInMs = minutes * 60 * 1000;

  var triggerTime = now + hoursInMs + minutesInMs;

  var interval = setInterval(function() {
    var now = Date.now();

    if(now >= triggerTime) {
      alert('timer!');

      // clear the interval to avoid memory leaks
      clearInterval(interval);
    }
  }, 0);
}

You'll save yourself a lot of bother if you use Date.now which returns the date as the number of milliseconds since the epoch. Then you can just treat the problem numerically, rather than messing with the date api.

Upvotes: 0

nitish koundade
nitish koundade

Reputation: 801

Find out the time remaining using Date function and then pass it on to setTimeout function.No need to keep on checking the time.

$(document).ready(function(){
 var d = new Date("November 19, 2015 17:00:00");
 var d1 = new Date();   
 var timelimit = (d.getTime() - d1.getTime());
    if(timelimit > 0)   {
        setTimeout(function(){
            console.log(12345);           
        },timelimit);
    }
  });

Upvotes: 4

Related Questions