Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading