问题
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