0

When the user clicks a button an interval will start counting but the problem is that if the user clicks the button two times there will be two intervals I tried clearInterval(interval); before assigning the interval but the timer stopped counting.

function times(){
    var element=document.getElementById("sec");
    counter=0;
    
    let interval= setInterval(myFunction, 1000);
        function myFunction(){
            counter++;
            element.innerHTML=counter;
        }

}

3 Answers3

0

if to want to clear the previously set interval when ever the user clicks, Just store the interval ID in a higher scope and clear the interval the previously set interval before creating a new one.

let interval 
function times(){
    clearInterval(interval);
    
    var element=document.getElementById("sec");
    counter=0;

    interval = setInterval(myFunction, 1000);
    
    function myFunction(){
        counter++;
        element.innerHTML=counter;
    }

}
Hariharan
  • 121
  • 4
0

You may try the following. Depending on the existence of the interval it is decided whether to (re-)start the timer or stop it.

let interval

function times(){
    var element=document.getElementById("sec");
    counter=0;
    
    if (interval) {
        clearInterval(interval)
        interval = null
    } else {    
        function myFunction(){
            counter++;
            element.innerHTML=counter;
        }
        element.innerHTML=counter; // just to show '0' when re-starting
        interval= setInterval(myFunction, 1000);
    }
}
<button onclick="times()">Start / Stop</button>

<span id="sec">0</span>
Lecraminos
  • 409
  • 6
0

document.querySelector('#sec').addEventListener('click', function() {
  times();
})

let interval;
let counter = 0;

function times() {
  clearInterval(interval);
  interval = setInterval(myFunction, 1000);
  counter = 0;
}

function myFunction() {
  var element = document.getElementById("sec");
  counter++;
  element.innerHTML = counter;
  console.log(counter);
}
<button id="sec">timer</button>
pier farrugia
  • 1,520
  • 2
  • 2
  • 9