Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove keydown delay in JavaScript?

Well, when you hold a key on your keyboard, after the first fire there is a 1sec delay.
You can go ahead and open notepad and hold a key (e.x 'x') you'll see after the first fire there is a delay.

However, I'm trying to develop a game in HTML5 Canvas with JavaScript, and that 1sec delay is very annoying, Additionally, it stops the player walking animation..

So how can I delete that annoying delay in JavaScript ( no jQuery! ) ?

My keydown event works in 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;
    }
}
like image 478
julian Avatar asked Jan 21 '13 23:01

julian


People also ask

What does Keydown do in Javascript?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

Should I use Keydown or Keyup?

KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.

What is Keydown event in jQuery?

jQuery keydown() Method keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.


1 Answers

you could start an 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 }
like image 160
Jason Avatar answered Sep 19 '22 17:09

Jason