'Hold button -> repeat function
I'm trying to achieve something which souldn't be hard to do, but everything I've tried so far hasn't worked.
I have a function that changes a value every time I click a button, and what I want is: when I hold this button, the value should keep changing.
This is what I've tried and hasn't worked, setInterval and setTimeout won't "wait" (the function get's called right away thousands of times and the website crashes):
$('.buttonPlus').mousedown(function() {
timeoutID =setTimeout(distribucionPorcentual($(this)),1000);
}).bind('mouseup mouseleave', function() {
clearTimeout(timeoutID);
});
Any help will be greately appreciated. Thanks!
Solution 1:[1]
I know this is a really old thread, but if someone stumbles upon it (I just did), you might find this useful. I needed to be able to do a simple increment, but if the mouse is held for a full second, then it goes into a rapid increment. Which is similar to how a keypress behaves on many systems.
$('#forward-step').mousedown(function() {
adjustPosition(1)
var cancel = false;
repeatDelayTimer = setTimeout( function() {
if (!cancel) {
repeatTimer = setInterval(function() {adjustPosition(1); },50);
}
},1000 )
t.bind('mouseup mouseleave', function() {
cancel = true;
console.log("Mouseup");
clearInterval(repeatTimer);
clearTimeout(repeatDelayTimer);
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | svenyonson |
