Tom C Tom C - 8 days ago 8
Javascript Question

Smooth keypress event handeling in Javascript?

I know its possible but I cant seem to figure it out. In its basic form I have a canvas circle moving 5 pixels every key event however this seems to be rather slow at firing and really jumpy, plus it stalls when changing key or changing from rapid key press to holding down.

So can someone enlighten me of a way ofwhich this could work without it stuttering?

Thanks.

Answer

What you want to do is set variables on keydown and keyup to true or false that you check every tick. Something like this:

var tickRate = 30,
    keyDown = {},
    keyMap = {
      'left':  37,
      'up':    38,
      'right': 39,
      'down':  40
    };

$('body').keydown(function(e){ keyDown[keyMap[e.which]] = true;  });
$('body').keyup(function(e){   keyDown[keyMap[e.which]] = false; });

var tick = function() {
  if        (keyDown['up']) {
    // up code
  } else if (keyDown['down']) {
    // down code
  } else if (keyDown['left']) {
    // left code
  } else if (keyDown['right']) {
    // right code
  }

  // other code

  setTimeout(tick, tickRate);
};

tick();
Comments