【问题标题】:Countdown timer in JavaScript not stoppingJavaScript中的倒数计时器没有停止
【发布时间】:2020-04-10 00:17:08
【问题描述】:

我有一个从 5:00 分钟开始倒计时的计时器,但它不会停止!它只是进入负面。 HTML

<p>Click the button to begin the quiz. Good Luck!</p>
            <button id="start" class="button">Start</button>    
            <div class="timer">
                Timer: <span id="time"> 5:00 </span> minutes
            </div>

JavaScript

document.getElementById('time').innerHTML = 05 + ":" + 00;

function startTimer() {
    var p_time = document.getElementById('time').innerHTML;
    var timeArray = p_time.split(/[:]+/);
    var min = timeArray[0];
    var sec = checkSecond((timeArray[1]-1));
    if(sec==59){min=min-1}
    if(min <= 0 && sec == 0) {alert("Time is up!")}

    document.getElementById('time').innerHTML = min + ":" + sec;
    setTimeout(startTimer, 1000);
}

function checkSecond(seconds) {
    if(seconds <10 && seconds >= 0) {seconds ="0" + seconds};
    if(seconds <0) {seconds = "59"};
    return seconds;
}

CSS

.timer {
    color: var(--primary);
    font-size: 16px;
    font-weight: bold;
    margin: 10px;
}

我有 JS 说,当分钟小于或等于 0 并且秒等于 0 时,会提示“时间到了”。所以我收到了弹出警报,但是一旦我在弹出窗口上单击“确定”,计时器就会一直倒计时为负数。 此外,在图片中,“5:00”没有出现 - 它只显示一个零。

【问题讨论】:

  • alert() 发生后,什么会阻止对setTimeout() 的后续调用?

标签: javascript html css timer


【解决方案1】:

你必须告诉它停止。例如。如果时间到了就返回。类似的东西

if(min <= 0 && sec == 0) {return alert("Time is up!")}
//                        ^ now the next statements won't run
document.getElementById('time').innerHTML = min + ":" + sec;
setTimeout(startTimer, 1000);

【讨论】:

    【解决方案2】:

    一旦定时器完成 5 分钟,您需要使用 clearTimeout 删除定时器。

    如果 stackoverflow sn-ps 不工作,请检查 - https://jsfiddle.net/e5v80xmk/

    document.getElementById('time').innerHTML = 05 + ":" + 00;
    document.getElementById('start').addEventListener('click', startTimer);
    
    var timerRef = null;
    
    function startTimer() {
      var p_time = document.getElementById('time').innerHTML;
      var timeArray = p_time.split(/[:]+/);
      var min = timeArray[0];
      var sec = checkSecond((timeArray[1] - 1));
      if (sec == 59) {
        min = min - 1
      }
    
      document.getElementById('time').innerHTML = min + ":" + sec;
    
      if (min <= 0 && sec == 0) {
        clearTimeout(timerRef)
        alert("Time is up!")
        return
      }
    
    
      timerRef = setTimeout(startTimer, 1000);
    }
    
    function checkSecond(seconds) {
      if (seconds < 10 && seconds >= 0) {
        seconds = "0" + seconds
      };
      if (seconds < 0) {
        seconds = "59"
      };
      return seconds;
    }
    <p>Click the button to begin the quiz. Good Luck!</p>
    <button id="start" class="button">Start</button>
    <div class="timer">
      Timer: <span id="time"> 5:00 </span> minutes
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多