Question

I would like to Add one every ms if user make long mousepress and stop at 10,

Something like that ?

$('#bar').mousedown(function(){
   setInterval(function() {
        for(i=1; i<11; i++){
            $('#foo').val(i);
        }
    }, 100);
});

JSfiddle :http://jsfiddle.net/9qeeg/

Was it helpful?

Solution 2

You could use clearInterval() and clear it when mouseUp or when you reach 10

var intVal = null;
var cnt = 0;
$('#bar').on('mousedown', function () {
    intVal = setInterval(function () {
        $('#foo').val(cnt);
        cnt == 10 ? clearInterval(intVal) : cnt++;
    }, 100);
}).on('mouseup', function () {
    clearInterval(intVal);
    if (cnt == 10) {
        cnt = 0
    }
});

DEMO

OTHER TIPS

Refactored a bit to avoid using a timeout and an interval:

var mouse = {
      interval:null, // reference to setInterval
      count: 0       // count
    };

// on mouse down, set an interval to go off every 100 ms. Every
// execution of this interval increases the counter by one.
// however, clear the interval (automatically) after 1000ms (100ms * 10)
$('#bar').on('mousedown', function(){
  // reset count (Can also fetch it from the input box if you'd like)
  mouse.count = 0;
  // establish interval that will run 10 times (with 100ms delay)
  mouse.interval = setInterval(function(){
    // increase count and place new value in the text field
    $('#foo').val(++mouse.count);
    // stop interval automatically when it reaches 10
    if (mouse.count == 10) {
      clearInterval(mouse.interval);
    }
  }, 100);
});

// Stop interval
// bind to the document to if the user's mouse strays from the button
// we still catch the event
$(document).on('mouseup', function(){
  if (mouse.interval){
    clearInterval(mouse.interval);
    mouse.interval = null;
  }
});

http://jsfiddle.net/xjs25/1/

Older version:

var mouse = {
      interval:null, // reference to setInterval
      timeout:null,  // reference to setTimeout
      count: 0       // count
    };

// on mouse down, set an interval to go off every 100 ms. Every
// execution of this interval increases the counter by one.
// however, clear the interval (automatically) after 1000ms (100ms * 10)
$('#bar').on('mousedown', function(){
  mouse.count = 0;
  mouse.interval = setInterval(function(){
    $('#foo').val(++mouse.count);
  }, 100);
  mouse.timeout = setTimeout(function(){
    clearInterval(mouse.interval);
  }, 100 * 10);
});

// Stop interval
// bind to the document to if the user's mouse strays from the button
// we still catch the event
$(document).on('mouseup', function(){
  mouse.interval && clearInterval(mouse.interval), mouse.interval = null;
  mouse.timeout && clearTimeout(mouse.timeout), mouse.timeout = null;
});

Your updated fiddle: http://jsfiddle.net/9qeeg/5/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top