0

I'm trying to make a timer within javascript. I want the timer to stop on click but it won't. I have two parameters: "start" and "stop". I want my program to restart the timer if the start button is clicked while the timer is already going and to stop when the stop button is clicked.

function timer(start, stop) {
let count;
if (start) {
    let count = 0;
    setInterval(() => {
        count++;
        console.log(count);
    }, 1000);
}
if (stop) {
    count = count;
}

}

1 Answers1

0

Just use clearInterval to stop the timer when it's running, and then set it again if they click when it's not running. Something like this:

var timer;
var running = false;
var elapsed = 0;
var div = document.getElementById('time');
document.getElementById('btn').addEventListener('click', function() {
    if (running) {
        clearInterval(timer);
        running = false;
    } else {
        timer = setInterval(function() {
            elapsed++;
            div.textContent = elapsed;
            }, 1000);
        running = true;
    }
});
<button id="btn">Click Me</button>
<div id="time"/>
dave
  • 62,300
  • 5
  • 72
  • 93