How to avoid keep double clicking continuously?
$('#element').dblclick(function(e){
console.log("event");
});
When I click the element at a开发者_如何学编程 very fast click, it shows the event many times. But I want the user prevent double clicking continuously, maybe skip it for 1 second, how can I do so?
var click_allowed = true;
$('#element').dblclick(function(e){
if (!click_allowed) return;
console.log("event");
click_allowed = false;
window.setTimeout(function() {
click_allowed = true;
}, 1000);
}
You can use .one
to ensure that your event handler runs only once, and then you can rebind it once enough time has elapsed (live demo):
function dblclickHandler(e){
console.log("event");
setTimeout(setHandler, 1000);
}
function setHandler() {
$('#element').one('dblclick', dblclickHandler);
}
setHandler();
I would use the doTimeout plugin, specifically the debounce feature: http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/. Try the first example on the second link I posted. Then, just modify it for double clicking instead of keyup
.
var lastClick = 0;
$('#element').dblclick(function(e){
var time = (new Date()).getTime();
if(time > lastClick + 1000) {
lastClick = time;
console.log("event");
}
}
精彩评论