繁体   English   中英

使用 clearInterval 清除并使用 setInterval 重置时,setInterval 不会重新启动

[英]setInterval won't restart when cleared with clearInterval and reset with setInterval

我有一个倒计时,它使用 setInterval 以一秒为间隔从一分钟开始倒计时。 单击“开始”按钮时,它将使用 setInterval(countdown, 1000) 开始倒计时。 当我单击另一个按钮时,它会清除倒计时。 如果我再次按下“开始”按钮,间隔不会再次使用 setInterval(countdown, 1000) 倒计时 - 它停留在一分钟。

我使用 setInterval 对吗? 一旦再次单击开始按钮,我希望 setInterval 以 1s 的间隔开始倒计时。

请在下面找到相关代码,感谢您的时间。

//Start button
$("#startQuiz").click(function () {
            $(".questionStart").css("display", "none").removeClass("questionActive");
            $(".questionStart").next().addClass("questionActive");

            startTimer = true;
            setInterval(countdown, 1000);

        });

//countdown code (at a global scope)
var countdown = setInterval(function () {

    if (startTimer === true) {    
            //timer code here
        }
    }

}, 1000);

//reset countdown code called on separate button click
function levelCloseReset() {
    startTimer = false;
    clearInterval(countdown);
}

尝试这个。

 (function() { let counter = null; let timer = 60; $("#startQuiz").click(function () { resetQuiz(); // reset the quiz; $(".questionStart").css("display", "none").removeClass("questionActive"); $(".questionStart").next().addClass("questionActive"); $("#startQuiz").attr("disabled", true); $("#stopQuiz").attr("disabled", false); $("#count-down").text("Time Remaining: " + timer); counter = setInterval(countDown, 1000); }); $("#stopQuiz").click(function () { $(".questionStart").css("display", "none").removeClass("questionActive"); $(".questionStart").next().addClass("questionActive"); $("#startQuiz").attr("disabled", false); $("#stopQuiz").attr("disabled", true); $("#count-down").text("Stopped: "); resetQuiz(); }); function countDown() { if(timer === 0) { $("#count-down").text("Time Over: "); $("#startQuiz").attr("disabled", true); $("#stopQuiz").attr("disabled", true); resetQuiz(); } else { $("#count-down").text("Time Remaining: " + --timer); } } function resetQuiz() { timer = 60; clearInterval(counter); } } )();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="count-down"></div> <button type="button" id="startQuiz">Start Quiz</button> <button type="button" id="stopQuiz" disabled>Stop Quiz</button>

暂无
暂无

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

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