Instead, listen when the key is pressed first, and then listen when it is released. It also means that you need to record the current state of the speed of movement, since you can apply it between these events.
In this example, there will only be a server to go forward, so it can be easily extended to other directions.
var playerSpeed = 0; document.onkeydown = keyDown; document.onkeyup = keyUp; function keyDown(e) { switch(e.keyCode) { case 38: // UP playerSpeed = 1; // moving! break; // other cases... } } function keyUp(e) { switch(e.keyCode) { case 38: // UP playerSpeed = 0; // NOT moving! break; // other cases... } } // Whatever loop is called for each frame or game tick function updateLoop() { // rendering, updating, whatever, per frame Player.PositionY += playerSpeed; }
So it doesn't matter what the keyboard repeat speed is. Every onkeydown will always have onkeyup . All you need to do and update things differently between these events.
source share