简体   繁体   English

延迟mousedown间隔启动(JQuery / Javascript)

[英]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. 我正在编写一个jQuery插件,按一下按钮即可操纵输入字段的值。

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 ) (您还可以在此处查看工作版本: 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. 但是,正如您在注释中看到的那样,我还希望当mousedown事件发生时,在值的初始增加之后,将interval函数延迟400ms,然后只执行一次。

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 . setInterval包装在setTimeout And, like interval , keep and clear a timeout value: 并且,像interval一样,保留并清除timeout值:

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/ http://jsfiddle.net/coiscir/jUSg8/

Here you go: http://jsfiddle.net/Hxhsh/10/ :) 在这里,您可以访问: http : //jsfiddle.net/Hxhsh/10/ :)

Just add a setTimeout 只需添加一个setTimeout

just use setTimeout to delay setInterval 只需使用setTimeout延迟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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM