jquery - Emptying keyboard buffer in javascript - Stack Overflow

admin2025-04-19  0

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));
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745073432a283426.html

最新回复(0)