Delay mousedown interval start (JQuery / Javascript)

半城伤御伤魂 提交于 2019-12-13 00:08:55

问题


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.


回答1:


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/




回答2:


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

Just add a setTimeout




回答3:


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);
}


来源:https://stackoverflow.com/questions/9968023/delay-mousedown-interval-start-jquery-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!