20

Is there to have a JavaScript function repeated every so many milliseconds that an html button is held down? It would be great if this could be done with standard JavaScript, but using jQuery or a jQuery plugin would be great too.

Brian
  • 26,662
  • 52
  • 135
  • 170

4 Answers4

32

On the mousedown() event, this code starts a repeating timer (every 500ms in this example) that is cancelled as soon as the mouseup() event occurs. This should be adaptable to what you want:

var intervalId;
$("#button").mousedown(function() {
  intervalId = setInterval(do_something, 500);
}).mouseup(function() {
  clearInterval(intervalId);
});

function do_something() {
  // whatever
}

See setInterval() for more information on clearing timers.

cletus
  • 616,129
  • 168
  • 910
  • 942
  • 2
    If you want the event to occur right away, AND every 500 milliseconds, just call `do_something()` immediately before calling setInterval. – Tyler Collier Jun 19 '12 at 09:23
  • @TylerCollier Thanks for pointing out. Then it works like the click event plus the repeated action. Very handy. In my case I also had to pass parameters, for this you have to do assign an anonymous function: `setInterval( function() { myfunction(valueA, valueB); }, 500 );` – Avatar Aug 10 '14 at 20:16
  • @TylerCollier can someone tell me why wont this stop? http://jsfiddle.net/oxpku7f1/1/ – SamuraiJack May 22 '15 at 04:47
  • 1
    @Arbaaz, it's the `alert()` call that causes this, because the normal flow (with the alert popping up) is disrupted. Change the alert to e.g. `console.log('a')` and it will stop when you mouseup. – Tyler Collier May 22 '15 at 04:59
7

I would use the javascript function setInterval() within a function that gets called on mouse down.

<input type="button" id="button" onmousedown="inter=setInterval(startAction, 1*1000);"
onmouseup="clearInterval(inter);" value="click here" />

<script type="text/javascript">
    function startAction(){
        //whatever you want done
    }
</script>
munch
  • 6,311
  • 4
  • 23
  • 27
7
var intervalId;
$("#button").mousedown(function() {
  intervalId = setInterval(do_something, 500);
}).mouseup(function() {
  clearInterval(intervalId);
}).mouseleave(function() {
//this should help solve the problem that occurs when the mouse leaves the button while pressed down
  clearInterval(intervalId);
});

function do_something() {
  // whatever
}
NotABlueWhale
  • 795
  • 7
  • 18
LordKayBanks
  • 71
  • 2
  • 2
6

I see a problem with both solutions listed above.

onmouseup is only triggered if the mouse is released while it is over the button. If the user keeps the mouse down then moves the mouse away before releasing it then clearInterval is never fired and so do_something will fire forever.

You would need to add another event, "onmouseout", that also calls clearInterval.

Dinesh Kanivu
  • 2,551
  • 1
  • 23
  • 55
user2931502
  • 61
  • 1
  • 1