how to increase number with holding button

Hello i want to increase number by holding down the button and stop increase when mouse up but it does not work properly its increasing when i use mouse down event but it does not stop when i use mouse up event

<div class="col-md-3"><button type="button" class="btn btn-success" id="secondButton" onmousedown="increase()" onmouseup="stop()">Up</button></div>

function myIntervalFunction() {
    number = number + 1;
    console.log(number);
}

function increase(){
    setInterval(myIntervalFunction,1000)
}

function stop() {
    clearInterval(increase())
}

>Solution :

You need to save the interval ID which setInterval() returns and then use that to clear the interval.

For details please see the linked MDN documentation.

let intervalId, number = 0;

function myIntervalFunction() {
  number = number + 1;
  console.log(number);
}

function increase() {
  intervalId = setInterval(myIntervalFunction, 1000)
}

function stop() {
  clearInterval(intervalId);
}
<div class="col-md-3">
  <button type="button" 
          class="btn btn-success" 
          id="secondButton" 
          onmousedown="increase()" 
          onmouseup="stop()">
        Up
  </button>
</div>

Leave a Reply