Search code examples
javascriptjquerysettimeoutsetintervalmousedown

Delay mousedown interval start (JQuery / Javascript)


I am writing a jQuery plugin that manipulates the value of an input field at the press of a button.

What I have so far is the ability to control the value by clicking the button, as well as to continually increase it if the user holds the button pressed. Simplified, the script is something like this:

var element = $('#test-input');
var interval;

$('#test-up-button').on({
    mousedown : function(e) {
        element.val(parseInt(element.val()) + 1);

        //Wait 400ms, than do the interval

        interval = window.setInterval(function() {
            element.val(parseInt(element.val()) + 1);
        }, 200);      
        e.preventDefault();        
    },
    mouseup : function() {
        window.clearInterval(interval);
    }
});

(You can also see a working version here: http://jsfiddle.net/Husar/Hxhsh/#base )

However, as you can see in the comment, I also want when the mousedown event happens, after the initial increase of the value, the interval function to be delayed for 400ms, and only than to execute.

So that you press the button, value goes + 1, you hold the button a bit, and than the intervals start to roll.


Solution

  • Wrap the setInterval in a setTimeout. And, like interval, keep and clear a timeout value:

    var interval, timeout;
    
    // ...
    
        timeout = window.setTimeout(function () {
            interval = window.setInterval(function() {
                element.val(parseInt(element.val()) + 1);
            }, 200);      
        }, 400);
    
    // ...
    
        window.clearTimeout(timeout);
        window.clearInterval(interval);
    

    http://jsfiddle.net/coiscir/jUSg8/