If I have an element that responses on
$('#div').keydown(function(event) { ....
and if user presses a key like a crazy rabbit on heat thousand times within a really short period, browser responses on most of those calls.
Can I somehow prevent that by flushing keyboard buffer?
If I have an element that responses on
$('#div').keydown(function(event) { ....
and if user presses a key like a crazy rabbit on heat thousand times within a really short period, browser responses on most of those calls.
Can I somehow prevent that by flushing keyboard buffer?
Share asked Sep 20, 2011 at 20:14 iLemmingiLemming 36.4k61 gold badges198 silver badges316 bronze badges 2- 1 What exactly are you trying to prevent? Fast typing? You can simply choose to ignore keystrokes that e within N ms of the previous key. – jfriend00 Commented Sep 20, 2011 at 20:20
- 1 Just make sure you do not block people who actually type fast. :) – epascarello Commented Sep 20, 2011 at 20:24
2 Answers
Reset to default 3This is an easy method to deal with an excessive number of keydown calls.
var timeout = false; //I'd remend defining this variable within a local scope
$('#div').keydown(function(event) {
if(timeout) return;
timeout = true;
setTimeout(function(){timeout=false}, 100);
//Change 100 to something more appropriate
//Rest of function
}
You may checkout the following blog post which illustrates how you could throttle down function calls and calm down the crazy rabbits.
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
$('input.username').keypress(debounce(function (event) {
// do the Ajax request
}, 250));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745073430a4609693.html
评论列表(0条)