Restart Timer Using Javascript

154 views Asked by At

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>
1

There are 1 answers

2
lbsn On

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");
};