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/