Remove keypress delay in JavaScript?

Well, when you hold the key on the keyboard, after the first operation there is a delay of 1 second.
You can open the notebook and hold the key (for example, "x") that you will see after the first fire.

However, I am trying to develop an HTML5 Canvas game with JavaScript, and this 1sec delay is very annoying. In addition, it stops the player’s walking animation.

So how can I remove this annoying delay in JavaScript (without jQuery!)?

My keystroke event works on this pattern -

document.onkeydown = getKey; function getKey(e) { switch(e.keyCode) { case 38: // UP Player.PositionY--; break; case 39: // RIGHT Player.PositionX++; break; case 40: // DOWN Player.PositionY++; break; case 37: // LEFT Player.PositionX--; break; } } 
+5
source share
3 answers

you can fire event on keydown and stop it on keyup

 $('#mycanvas').on('keydown', function() { $(document).trigger('start'); }); $('#mycanvas').on('keyup', function() { $(document).trigger('stop'); }); $(document).on('start', startAnimation); $(document).on('stop', stopAnimation); function startAnimation(e) { //start something } function stopAnimation(e) { //stop something } 
+3
source

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.

+1
source

You're in luck, I'm just coding this for the game.

 Controller = { keyIsDown: [], // Add a new control. up is optional. // It avoids key repetitions add: function (key, down, up) { $(document).keydown(function(e) { if(e.keyCode === key && !Controller.keyIsDown[key]) { down() Controller.keyIsDown[key] = true return false } }) $(document).keyup(function(e) { if(e.keyCode === key) { if(up) up() Controller.keyIsDown[key] = false return false } }) }, } 

Example:

 Controller.add(65, function () { console.log("A is down") }, // This argument is optional function () { console.log("A is up") }) 
+1
source

All Articles