jquery - Emptying keyboard buffer in javascript - Stack Overflow

If I have an element that responses on $('#div').keydown(function(event) { ....and if user pr

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
Add a ment  | 

2 Answers 2

Reset to default 3

This 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

相关推荐

  • jquery - Emptying keyboard buffer in javascript - Stack Overflow

    If I have an element that responses on $('#div').keydown(function(event) { ....and if user pr

    14小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信