0

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. 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>
wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29
qyioma
  • 15
  • 6

1 Answers1

1

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. So assuming you have a button like this in your HTML:

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

you can add a resetCounter() function in your code:

var resetCounter = () => {
  value = seconds;
  localStorage.removeItem("counter");
};
lbsn
  • 2,322
  • 1
  • 11
  • 19
  • I try to use your code, but when I click the reset button, I cannot go to the next page(.php) that consist of my questions and timer. – qyioma Apr 21 '21 at 01:49
  • You didn't mention nor shared any php code in you question and in principle there is nothing in my code preventing you from navigating to a new page. So I suggest you add some more details to your question about what you're trying to accomplish. – lbsn Apr 21 '21 at 07:16