微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Typescript 中创建警报时出现问题但警报不起作用

如何解决在 Typescript 中创建警报时出现问题但警报不起作用

我正在使用打字稿创建闹钟,但遇到了问题。当时间过去时,我不会感到惊慌。 我从 HTML 页面获取了三个输入 - 小时分钟

之后我将它们相加并减去当前时间。

    let h = <HTMLInputElement>document.getElementById("h");//getting input values of hour and ...
    let m = <HTMLInputElement>document.getElementById("m");
    let s = <HTMLInputElement>document.getElementById("s");

    let h1 = parseFloat(h.value);//converting the input values from string to float
    let m1 = parseFloat(m.value);
    let s1 = parseFloat(s.value);

    var rHours = new Date().getHours();
    var rMinutes = new Date().getMinutes();
    var rSeconds = new Date().getMinutes();
    var calc = (h1) + (m1) + (s1) - rHours - rMinutes - rSeconds;
    
    if(calc<=0){
       alert("Alarm");
    }
}

但它不能正常工作。

解决方法

我已经有一段时间没有构建倒数计时器了,所以我想我会这样做是为了好玩。这不是特别是 Typescript,但它在编译器中运行得很好(见下面的链接)。它是常规的 JS,因此它也将在代码段中运行。我认为它可以帮助您了解倒数计时器的工作原理。您的代码没有反映任何倒计时,并且您确定经过时间的方法不正确。

出于演示的目的,我将 h1m1s1 设置为从代码段运行时起动态 1 分钟。您可以轻松地将其调整为使用您的输入元素。

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。