Masnad Nihit Masnad Nihit - 9 months ago 41
Javascript Question

Making a alarm clock with date time

I am trying to make a alarm clock that will fire a sound when its done.
so I input time as lets say alarm should start at 18:00:00 and the current time is 17:59:00 so basically the alarm should fire off in 1 min.
I tried doing it in this way.

var x = '18:00:00';
var t = new Date(x) - new Date();
setTimeout(function(){ alert("Hello"); }, t);


This doesnt work, not sure why. Error is NaN

Answer Source

Your problem is the way that x is defined. The logic behind your code is solid, however you need to use some reasonably smart Datetime manipulation to achieve this. As an example, let's set the alarm for five seconds from the time the page is loaded:

x = new Date();
x.setSeconds(x.getSeconds() + 5);
var t = new Date(x) - new Date();
setTimeout(function(){ alert("Hello"); }, t);

I would suggest you look into Date and figuring out the logic and methods that you need to use to solve your problem.

A rough solution

The logic for an alarm based solely on hours should be like this:

  • Create a dummy date from the HH:mm:ss of the alarm time, using the current day, month etc.
  • Compare to a new Date() to see if it is before or after the current date.
  • If before the current date, then set x to tomorrow and the HH:mm:ss you were given.
  • Otherwise set to today and the HH:mm:ss.
  • Subtract the dates and deal with the alarm.

The following code demonstrates how to implement this:

var x = {
  hours: 18,
  minutes: 0,
  seconds: 0
};

var dtAlarm = new Date();
dtAlarm.setHours(x.hours);
dtAlarm.setMinutes(x.minutes);
dtAlarm.setSeconds(x.seconds);
var dtNow = new Date();

if (dtAlarm - dtNow > 0) {
  console.log('Later today, no changes needed!');
}
else {
  console.log('Tomorrow, changing date to tomorrow');
  dtAlarm.setDate(dtAlarm.getDate() + 1);
}

var diff = dtAlarm - new Date();
setTimeout(function(){ alert("Hello"); }, diff);

Notes:

  • HH:mm:ss refers to the hours:minutes:seconds format (see here for more).
  • I am also using an object in place of your x to make conversion easier. You can easily build the object from a string.