if button is keeping pressed execute increment javascript code example

Example: if button is keeping pressed execute increment javascript

var timeout;
var speed = 500;

// Increment button
$('#plus-btn').on('mousedown mouseup mouseleave', e => {
  if (e.type == "mousedown") {
    increment(speed);
  } else {
    stop()
  }
});

// Increment function
function increment(speed) {
  $('#qty-input').val(parseInt($('#qty-input').val()) + 1);
  timeout = setTimeout(() => {
    increment(speed * 0.8);
  }, speed);
}

function stop() {
  clearTimeout(timeout);
}

Tags:

Misc Example