简体   繁体   English

JavaScript 倒数计时器计数过零

[英]JavaScript countdown timer counting past zero

This might be a really simple thing to ask but I've got a JavaScript countdown timer, but I can't stop it from counting past 0:00.这可能是一个非常简单的问题,但我有一个 JavaScript 倒数计时器,但我无法阻止它从 0:00 开始计数。 Instead of stopping at this point, it will continue to -1:59 etc.它不会在此时停止,而是会继续到 -1:59 等。

I'd also like it to play a beeping sound (which can be found here ) when the timer reaches zero.我还希望它在计时器达到零时播放哔声(可以在此处找到)。

This is the code I've got so far:这是我到目前为止的代码:

<div class="stopwatch">
  <div class="circle">
    <div class="time" id="timer"></div>
  </div>
</div>

<script>
  document.getElementById('timer').innerHTML =
    02 + ":" + 30;
  startTimer();

  function startTimer() {
    var presentTime = document.getElementById('timer').innerHTML;
    var timeArray = presentTime.split(/[:]+/);
    var m = timeArray[0];
    var s = checkSecond((timeArray[1] - 1));
    if(s==59){m=m-1}

    document.getElementById('timer').innerHTML =
      m + ":" + s;
    console.log(m)
    setTimeout(startTimer, 1000);
  }

  function checkSecond(sec) {
    if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
    if (sec < 0) {sec = "59"};
    return sec;
  }
</script>

Any help on this would be appreciated.对此的任何帮助将不胜感激。

To stop the counter when it reaches zero you have to stop calling the startTimer() function.要在计数器达到零时停止计数器,您必须停止调用 startTimer() function。 In the following snippet I have implemented a check to do exactly that.在下面的代码片段中,我已经实现了一个检查来做到这一点。

function startTimer() {
    var presentTime = document.getElementById('timer').innerHTML;
    var timeArray = presentTime.split(/[:]+/);
    var m = timeArray[0];
    var s = checkSecond((timeArray[1] - 1));
    if(s==59){m=m-1}

    document.getElementById('timer').innerHTML =
      m + ":" + s;
    console.log(m)
    // Check if the time is 0:00
    if (s == 0 && m == 0) { return };
    setTimeout(startTimer, 1000);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM