Skip to content
Advertisement

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!

Answer

Your code was a jumbled mess of mistakes (one misplaced semicolon, two missing brackets etc). On any modern browser, JS would’ve prevented the events from binding – were you testing on IE?

IF you were, here is a corrected version: http://tinker.io/fd2da . I’ve also fixed a little problem of scope in the setTimeout call (this is null in a setTimeout closure call).

the code:

 // stub the calls
 function distribucionPorcentual(arg) {
 }
 function distribution(arg) {
    console.log(arg);
 }
 $(document).ready(function(){
    $('.buttonPlus').mousedown(function() {
    console.log("Test");
        distribucionPorcentual($(this));
    var t = $(this);
       timeoutID =setTimeout(function() {distribution(t); },1000);
    }).bind('mouseup mouseleave', function() {
    console.log("Mouseup");
    clearTimeout(timeoutID);
    });
 });

You may want to bind the mouseup/mouseleave inside the setTimeout to save yourself from having to have to deal with a global variable.

Advertisement