Skip to content Skip to sidebar Skip to footer

Keydown (repetition) Breaks When Keyup Event (for Another Key) Is Fired

This is a bit of a weird one so I figure I'm either missing something obvious or this is a flaw with how these events are implemented in browsers. Let me first summarize an example

Solution 1:

That is the way the OS/environment works, and as a result that is the way the browser works.

The keydown repetition shouldn't continue firing after the keyup from another key in the browser, since it doesn't behave that way anywhere else. Open Notepad, or vim, or pico, or whatever text editor you use, and perform the same sequence of events. You'll see that after the keyup, the first key you pressed does not keep printing new letters. That's just the way these things were designed in the OS, and as a result that's the way they're propogated through to the editors and browsers etc.

Solution 2:

Here is my system for my keyboard input. You can see how the repeating key can be extracted for your own use here. It will allow you to notice held keys and not rely on an Operating system as another answer incorrectly assumed.

var down = [140]; //make an array to cover all the keypresses you should need with a normal keyboarddocument.addEventListener('keydown', function(event) {
  if (down[event.keyCode]){
    return;
  } else {
   //do the normal things you do when you get key presses
  down[event.keyCode]=true;
  }
}, true);
document.addEventListener('keyup', function(event) {
  down[event.keyCode]=false;
   //do the normal things you do when you get key releases
}, true);

You can just check for the array "down" and the position within it of whatever keycode you want. I use it to prevent keyrepeats for game input. Hope this helps!

Solution 3:

For future readers, you can try this.

let keys = {};

document.onkeydown = e => {
  if (!keys[e.code]) {
    keys[e.code] = true;
  }
};

document.onkeyup = e => (keys[e.code] = false);

move = () => {
  if (keys["ArrowLeft"]) {
    console.log("ArrowLeft")
  }
  if (keys["ArrowRight"]) {
    console.log("ArrowRight")
  }
  if (keys["ArrowDown"]) {
    console.log("ArrowDown")
  }
  if (keys["ArrowUp"]) {
    console.log("ArrowUp")
  }
};

setInterval(move, 100);

Post a Comment for "Keydown (repetition) Breaks When Keyup Event (for Another Key) Is Fired"