Possible Duplicate:
JavaScript move delay and multiple keystrokes
I’m new and learning HTML5 canvas together with javascript. I’ve created an event to move an object left and right, and my problem is the delay whenever you hold the key or switch to another key. I know there’s missing on my code below please help me. Thank you in advance.
c.addEventListener('keydown',this.check,true);
function check(el) {
var code = el.keyCode || el.which;
if (code == 37 || code == 65){
x -=1;
}
if (code == 39 || code == 68){
x += 1;
}
el.preventDefault();
}
Rather than trying to react directly to the keydown event, I’d suggest you use the keydown and keyup events to maintain a list of which keys are presently down. Then implement a “game loop” that checks every x milliseconds which keys are down and update the display accordingly.
You’ll notice that this lets you handle multiple keys at once, e.g., if the user presses the left and up arrows together, and the problem of delay between subsequent keydown events when a key is held down goes away since all you really care about is whether a keyup has occurred.
I realise you may not be implementing a game, but this “game loop” concept should work for you as shown in this very simple demo: http://jsfiddle.net/nnnnnn/gedk6/