문제

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.

도움이 되었습니까?

해결책

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/

다른 팁

Here you go: http://jsfiddle.net/Hxhsh/10/ :)

Just add a setTimeout

just use setTimeout to delay setInterval

mousedown: function(e) {
    setTimeout(function() {
        interval = window.setInterval(function() {
            element.val(parseInt(element.val()) + 1);
        }, 200);
    }, 400);
    e.preventDefault();
},
mouseup: function() {
    window.clearTimeout(timeout);
    window.clearInterval(interval);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top