倒计时器重置问题

时间:2016-12-22 06:11:10

标签: javascript setinterval

当我转到下一个问题时,计时器从一开始就开始 - 这意味着,当我开始参加考试 n 时,我已经将我的计时器设置为5分钟但是当我转到对于每个 n 每个问题,计时器从5分钟开始的下一个问题。我想在开始测验时为我的整个测验设置相同的计时器,并且它不会重置为每个问题的新时间(即5分钟)。

function startTimer(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        // get the number of seconds that have elapsed since 
        // startTimer() was called
        diff = duration - (((Date.now() - start) / 1000) | 0);

        // does the same job as parseInt truncates the float
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds; 

        if (diff <= 0) {
            // add one second so that the count down starts at the full duration
            // example 05:00 not 04:59
            start = Date.now() + 1000;
        }
    };
    // we don't want to wait a full second before the timer starts
    timer();
    setInterval(timer, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<body>
    <div>Registration closes in <span id="time"></span> minutes!</div>
</body>

1 个答案:

答案 0 :(得分:0)

  

“当我转到下一个问题时”

你如何转向下一个问题?整页加载?

你有一个window.onload事件,如果重新加载窗口,它将重置计时器...是否在转移到下一个问题时重新加载窗口?

这个问题需要更多信息。