JavaScript 中的倒计时器没有停止

我有一个计时器,从 5:00 分钟开始倒计时,但它不会停止!它只会变得消极。超文本标记语言


<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”没有显示 - 它只显示一个零。

https://img1.sycdn.imooc.com/656d8f560001313b08070348.jpg

慕盖茨4494581
浏览 108回答 2
2回答

慕容3067478

你必须告诉它停止。例如,如果时间到了就返回。就像是if(min <= 0 && sec == 0) {return alert("Time is up!")}//&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ^ now the next statements won't rundocument.getElementById('time').innerHTML = min + ":" + sec;setTimeout(startTimer, 1000);

慕仙森

clearTimeout计时器完成 5 分钟后,您需要删除计时器。如果 stackoverflow 片段不起作用,请检查此 -&nbsp;https://jsfiddle.net/e5v80xmk/document.getElementById('time').innerHTML = 05 + ":" + 00;document.getElementById('start').addEventListener('click', startTimer);var timerRef = null;function startTimer() {&nbsp; var p_time = document.getElementById('time').innerHTML;&nbsp; var timeArray = p_time.split(/[:]+/);&nbsp; var min = timeArray[0];&nbsp; var sec = checkSecond((timeArray[1] - 1));&nbsp; if (sec == 59) {&nbsp; &nbsp; min = min - 1&nbsp; }&nbsp; document.getElementById('time').innerHTML = min + ":" + sec;&nbsp; if (min <= 0 && sec == 0) {&nbsp; &nbsp; clearTimeout(timerRef)&nbsp; &nbsp; alert("Time is up!")&nbsp; &nbsp; return&nbsp; }&nbsp; timerRef = setTimeout(startTimer, 1000);}function checkSecond(seconds) {&nbsp; if (seconds < 10 && seconds >= 0) {&nbsp; &nbsp; seconds = "0" + seconds&nbsp; };&nbsp; if (seconds < 0) {&nbsp; &nbsp; seconds = "59"&nbsp; };&nbsp; return seconds;}<p>Click the button to begin the quiz. Good Luck!</p><button id="start" class="button">Start</button><div class="timer">&nbsp; Timer: <span id="time"> 5:00 </span> minutes</div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5