Skip to content
Advertisement

Remove key press delay in Javascript

I have the following problem: I’m trying to write a Javascript game, and the character is being controlled by the arrow keys.
The problem is, when one keeps the key pressed, there is a short delay between firing the first keypress and the repeated keypress.
Also, when one presses the “right arrow key” and keeps it pressed, and then presses the “up arrow key” the character doesn’t move to the top right corner, but stops the moving in the right direction and starts moving up.
This is the code I’m using:

JavaScript
function Pressed(e) { 
        cxc = e.keyCode;
        if(cxc == 37)
            Move(-1,0);
        if(cxc == 38)
            Move(0,-1);
        if(cxc == 39)
            Move(1,0);
        if(cxc == 40)
            Move(0,1);
    }

Does anybody have an idea?

Advertisement

Answer

If you want key repeat in a controllable fashion, you will have to implement it yourself, as keypress events are fired dependent on the OS’s idea of how keys should repeat. That means there may be variable initial and following delays, and holding down two keys at once will cause only one of them to repeat.

You will have to keep a record of whether each key is currently pressed, and ignore keydown events when the key is already down. This is because many browsers will fire a keydown as well as a keypress event when an autorepeat occurs, and if you’re reproducing key repeat yourself you’ll need to suppress that.

For example:

JavaScript

then:

JavaScript

Although, most action-based games have a fixed-time main frame loop, which you can tie the key up/down handling into.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement