Skip to content Skip to sidebar Skip to footer

Problem In Creating An Alarm In Typescript But The Alarm Isn't Working

I am creating an alarm clock using typescript and I am facing in issue. I am not being alarmed when the time passes. I have taken three inputs from the HTML page – Hours, Minutes

Solution 1:

I've haven't built a countdown timer in a while, so I thought I'ddo it for fun. This isn't especially Typescript, but it does run just fine in the compiler (see link below). It's regular JS so it will run in the snippet as well. I thought it might help you see how a countdown timer would work. Your code didn't reflect any kind of countdown, and your method of determining elapsed time was incorrect.

For the purposes of the demo, I set h1, m1 and s1 to dynamically be 1 minute from whenever the snippet is run. You can easily adapt this to work from your input elements.

document.querySelector('p span').innerHTML = new Date().toString()

function startCountdown() {
/* In your code uncomment this section...
    let el_h = <HTMLInputElement>document.getElementById("h");
    let el_m = <HTMLInputElement>document.getElementById("m");
    let el_s = <HTMLInputElement>document.getElementById("s");
*/

  // in your code comment out these lines and use yours from above instead (for typescript typing)
  let el_h = document.getElementById("h");
  let el_m = document.getElementById("m");
  let el_s = document.getElementById("s");


  let h1 = parseFloat(el_h.value);
  let m1 = parseFloat(el_m.value);
  let s1 = parseFloat(el_s.value);


  //const [h1, m1, s1] = ( (new Date().getHours() ) + ":" + (new Date().getMinutes() + 2) + ":" + new Date().getSeconds()).split(":");

  // get todays date
  let today = new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate();

  // add on the hours from the inputs
  today += " " + h1 + ":" + m1 + ":" + s1;
  const myTime = new Date(today);

  console.log('countdown to:', myTime, 'from:', new Date());
  const interval = setInterval(() => {
    let diff = (myTime.getTime() - new Date().getTime()) / 1000; // seconds
    let h = Math.floor(diff / 3600);
    let m = Math.floor(diff / 60 % 60);
    let s = Math.floor(diff % 60)
    console.log(h + " hours, " + m + " minutes, " + s + " seconds")
    if (diff <= 0) {
      clearInterval(interval);
      console.log("ALARM");
    }
  }, 1000)
}
<p>Cur time: <span></span></p>
<input id='h' placeholder='Hour (military time)'><input id='m' placeholder='Minute'><input id='s' placeholder='Seconds'><button onclick='startCountdown()'>Start</button>

tsplayground link


Post a Comment for "Problem In Creating An Alarm In Typescript But The Alarm Isn't Working"