0

我尝试使用 JavaScript 为我的测验设置计时器。(setInterval)但如果我提前完成测验并单击开始按钮增益,时间将在我停止测验时开始计数。再次单击开始按钮后如何重新开始时间?.

<script>
    var seconds = 40;
    if (localStorage.getItem("counter")) {
        if (localStorage.getItem("counter") <= 0) {
            var value = seconds;
            alert(value);
        } else {
            var value = localStorage.getItem("counter");
        }
    } else {
        var value = seconds;
    }
    document.getElementById("divCounter").innerHTML = value;

    var counter = function() {
        if (value <= 0) {
            localStorage.setItem("counter", seconds);
            value = seconds;
        } else {
            value = parseInt(value) - 1;
            localStorage.setItem("counter", value);
        }
        document.getElementById("divCounter").innerHTML = value;
    };

    var interval = setInterval(function() { counter(); }, 1000);
</script>
4

1 回答 1

1

根据您当前的代码,您需要执行什么来重置计数器value=seconds并删除localStorage. 因此,假设您的 HTML 中有这样的按钮:

<button type"button" onclick="resetCounter()">Reset</button>

您可以在代码中添加一个resetCounter()函数:

var resetCounter = () => {
  value = seconds;
  localStorage.removeItem("counter");
};
于 2021-04-20T07:49:27.913 回答