[英]Restart Timer Using Javascript
I try to use JavaScript to set timer for my quiz.(setInterval) but if I finish the quiz earlier and click on start button gain, the time will start counting at the time I stop the quiz.我尝试使用 JavaScript 为我的测验设置计时器。(setInterval)但如果我提前完成测验并单击开始按钮增益,时间将在我停止测验时开始计数。 How can I restart the time after I click on the start button again?再次单击开始按钮后如何重新开始时间? . .
<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>
Based on your current code what you need to do to reset the counter is set value=seconds
and removing the current value in localStorage
.根据您当前的代码,重置计数器所需的操作是设置value=seconds
并删除localStorage
中的当前值。 So assuming you have a button like this in your HTML:因此,假设您的 HTML 中有这样的按钮:
<button type"button" onclick="resetCounter()">Reset</button>
you can add a resetCounter()
function in your code:您可以在代码中添加 resetCounter resetCounter()
function:
var resetCounter = () => {
value = seconds;
localStorage.removeItem("counter");
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.