如果答案错误,则从计时器中减去时间,创建测验JavaScript

问题描述 投票:0回答:1

为课堂上的项目创建测验。测验正在工作,但我为计时器感到困惑。当您按下开始按钮时,计时器将执行并开始倒计时。选择并提交测验中错误的答案后,如何减少计时器的时间?

[谢谢,很抱歉,如果我错过了已经回答了这个问题的帖子。

计时器代码:

function startTimer(){
    console.log('timer suppose to go')
    var sec = 59;
    var timer = setInterval(function(){
        document.getElementById('timerDisplay').innerHTML='00:'+sec;
        sec--;
        if (sec < 0) {
            clearInterval(timer);
            alert("Time is up!")
        }
    }, 1000);
}
javascript
1个回答
0
投票

您只需要确保可以访问该功能之外的sec,然后在他们得到错误答案时递减(并更新显示):

(function() {
    var sec = 60;
    function startTimer(){
        console.log('timer suppose to go')
        var timer = setInterval(function(){
            sec--;
            document.getElementById('timerDisplay').innerHTML='00:'+sec;
            if (sec < 0) {
                clearInterval(timer);
                alert("Time is up!")
            }
        }, 1000);
    }
    document.getElementById('incorrect').addEventListener('click', function() {
        sec -= 5;
        document.getElementById('timerDisplay').innerHTML='00:'+sec;
    });
    startTimer();
})();
<div id="timerDisplay"></div>
<button id="incorrect">Simulate Incorrect Answer</button>
© www.soinside.com 2019 - 2024. All rights reserved.