-1

I need to execute a javascript function continuosly (every second or half a second for example), but this needs to happen while a button is pressed.

I tried with the following:

$("#buttonID").bind('touchstart',function(event){ 
        setInterval(function() {
            FUNCTION
        }, 1000);
    });

It is not working that way, using "mousedown" either.

What it's answered on question JavaScript while mousedown did not solve my issue, so I don't consider this question as a duplicate.

Is there a beginner's mistake and I'm not seeing it? what do you suggest?

Luz A
  • 41
  • 1
  • 10

1 Answers1

5

You have to capture a reference to the timer and cancel it when the mouse is released.

var timer = null; // Will hold a reference to the timer

$("#buttonID").on('mousedown',function(event){ 
 // Set the timer reference
 timer = setInterval(function() {
   console.log("Function running");
 }, 1000);
});

$("#buttonID").on('mouseup',function(event){ 
 clearInterval(timer);  // Cancel the timer
 console.log("Timer cancelled.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonID">Hold me down to run function!</button>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71