Incrementing value continuously on mouse hold

You can use requestAnimationFrame to constantly check if any button is still pressed. If still pressed, you can increment or decrement your value.

  • Create a ‘number’ variable that starts at zero.
  • If the Add button is pressed, set an ‘isDown’ variable to 1.
  • If the Subtract button is pressed, set the ‘isDown’ variable to -1.
  • If any button is released, set the ‘isDown’ variable to 0;
  • Start a requestAnimationFrame loop that constantly checks if ‘isDown’ is not zero. If not zero, requestAnimationFrame changes the ‘number’ variable by the isDown value.

Here’s example code and a Demo:

var $result=$('#result');
var number=0;
var isDown=0;
var delay=250;
var nextTime=0;

requestAnimationFrame(watcher);

$("button").mousedown(function(e){handleMouseDown(e);});
$("button").mouseup(function(e){handleMouseUp(e);});
$("button").mouseout(function(e){handleMouseUp(e);});


function handleMouseDown(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  // Put your mousedown stuff here
  isDown=(e.target.id=='Add')?1:-1;
}

function handleMouseUp(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  // Put your mouseup stuff here
  isDown=0;
}

function watcher(time){
  requestAnimationFrame(watcher);
  if(time<nextTime){return;}
  nextTime=time+delay;
  if(isDown!==0){
    number+=isDown;
    $result.text(number);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id=Add>Add</button>
<button id=Subtract>Subtract</button>
<span id='result'>0</span>

Leave a Comment