Reputation:
I'm struggling with finding a way to add a short 200 ms delay after a keydown event.
This is to prevent someone from pressing the keys too fast one right after the other.
Here is the code currently:
$(document).keydown(function (e) {
if ($(e.target).is('input')) { e.stopPropogation(); }
else if (e.keyCode == 37) { $(".pageback").click(); return false; }
if (e.keyCode == 39) { $(".pagenext").click(); return false; }
});
Upvotes: 0
Views: 635
Reputation: 484
You can't prevent someone from pressing the key too quickly, and it's probably unwise/impossible to stop the message from coming. however, you can track the time since the last key press and ignore the message if it's too soon:
var last_time = null;
$(document).keydown( function (e) {
var now = new Date().getTime(),
diff;
if ($(e.target).is('input')) {
e.stopPropogation();
} else if (e.keyCode == 37 || e.keyCode == 39) {
if( last_time != null ) {
diff = now - last_time;
if( diff < 200 ) {
return false; // do nothing
}
}
last_time = now;
if (e.keyCode == 39) {
$(".pageback").click();
return false;
} if (e.keyCode == 39) {
$(".pagenext").click();
return false;
}
}
});
Each time a key is pressed, the time since the last successful press is checked and if there has been enough delay, record the current time and carry on. Otherwise, drop out.
Make sense?
Upvotes: 2
Reputation: 318182
var timer;
$(document).on('keydown', function (e) {
clearTimeout(timer);
timer = setTimeout(function() {
if ($(e.target).is('input')) {
e.stopPropogation();
}else if (e.keyCode == 37) {
e.preventDefault();
$(".pageback").click();
}
if (e.keyCode == 39) {
e.preventDefault();
$(".pagenext").click();
}
}, 200);
});
Use a simple timeout that clears when a key is pressed, that way the function won't execute if the user is typing faster than one key every 200ms.
Upvotes: 0