How to avoid multiple up / down keys / key presses while holding a key?

I am creating a web interface for controlling a small robot. Ajax calls will be made when a key is pressed, the robot starts and the keyboard locks to stop it.

My problem is that when a key is held down by a keystroke, the keydown, keydown, and keypress events seem to be constantly cycling. Does anyone know of a way to have only fire on startup the first time a key is pressed and the keyboard fired when it was released?

- edit: I forgot to mention this initially, but I tried to save the state of the button. The problem is that the keydown, keypress, and keyup events fire again and again when I hold the key down.

+3
source share
3 answers

I cannot reproduce the problem, I cannot find any events in Keyup, no matter how long I hold the key.

This method listens for key start, runs some code, and waits for keystrokes before listening for another keystroke.

A warning is triggered only when a key is pressed.

var A=[], who=// I used a textarea, substititute your own target
who.onkeydown= who.onkeyup= function(e){
 e=window.event || e;
 var t= e.type, target= e.target || e.srcElement;
 A.push(t);
 if(t== 'keydown'){
  // start robot and stop listening to keydown
  target.onkeydown= '';
 }
 else if(t== 'keyup'){
  // stop robot and listen for keydown
  target.onkeydown= arguments.callee;
  alert(A)
 }
}
+2
source

You can try to save the key state. When the key is lowered, check if the key is pressed, if not, start the robot and mark the key pressed. If it is already pressed, do nothing. On the keyboard, do the same to stop the robot and mark the key as not pressed.

0
source

, keyup, .

keyup, .

EDIT: keydown. keydown keyup... .

So basically:

  • assign a keydown event handler
  • assign keyup event handler
  • when opening the key, remove the keydown event handler and start your robot.
  • on the keyboard, re-assign the keydown event handler
0
source

Source: https://habr.com/ru/post/1735931/


All Articles