0

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.

Hunt
  • 8,215
  • 28
  • 116
  • 256

2 Answers2

4

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);
    }
  });
nitish koundade
  • 801
  • 5
  • 12
0

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.

Community
  • 1
  • 1
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
  • Not passing a `delay` to `setInterval` doesn't work for me in Firefox. Works in Chrome, but Firefox I think you'll need to pass 0 explicitly (although that's probably overkill for what the OP wants anyway). – Daniel Flint Nov 19 '15 at 11:14
  • Yep, just a typo. Fixed now – Dan Prince Nov 19 '15 at 12:23
  • You're saying that `setInterval()` should be called with `delay` of 0? That's effectively like polling in a tight loop, no? Seems hardly efficient. – jrc Mar 06 '20 at 12:18
  • @jrc It's terribly inefficient, but it guarantees some more accuracy than `setTimeout`. These days I would use `requestAnimationFrame` instead, but if you're building a long running timer, using a low resolution `setTimeout` is probably best. – Dan Prince Mar 06 '20 at 15:07