Search code examples
javascriptjquerykeycode

Event when space is pressing, only one time


I have some issues: I have this : (in a function..)

var space = 0;

setInterval(space, 20);
var keys = {}

$(document).keydown(function(e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
    delete keys[e.keyCode];
});

function space() {
    for (var direction in keys) {
        if (!keys.hasOwnProperty(direction)) continue;
        if (direction == 32) {
                space++;
                console.log(space);
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

32 == Space key, but I saw in the console that space is pressed 3 times (space == 3), keyup keypress and keydown (I think), how can I have just "space = 1" when space is pressed ?


Solution

  • What seems to be happening is that since it's running every 20 ms, as you hold down the space bar the space function is continuously incrementing the count. I added a flag to prevent another execution until the key is released and it works fine. Really you should just use the keypress event and check there if the keyCode === 32 to track your count. Fewer events will be fired. If you want to see what was happening you can comment out the flag and check the console.

    var spaceCount = 0;
    var running = false;
    var keys = {}
    
    $(document).keydown(function(e) {
      console.log("keycode", e.keyCode);
      keys[e.keyCode] = true;
    });
    
    $(document).keyup(function(e) {
      console.log("keyup")
      delete keys[e.keyCode];
      running = false;
    });
    
    function space() {
      if(running) return;
      for (var direction in keys) {
        running = true;
        console.log(direction);
        if (!keys.hasOwnProperty(direction)) continue;
        if (direction == 32) {
          spaceCount++;
          console.log("count: " + spaceCount);
          console.log(keys);
        }
      }
    }
    
    setInterval(space, 20);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>