2

I have a function that runs every frame on my website. Inside it, there is a key press check, that if I press a key, it gets fired at least a 100 times. How can I prevent this?

I've tried slowing down my FPS using a wait function, but to get it to work I have to slow it down to around 5 FPS, which is too slow.

Here is the code inside the function that runs forever (I'm using socket.io, so there is a bit of that in there. Don't mind it):

    // Rendering
    $('#svg').empty();
    for (var i = 0; i < players.length; i++){
      var circle = makeSVG('circle', {cx: players[i].x, cy: players[i].y, r: '5vw', stroke: '#00FFFF', 'stroke-width': '0px', fill: '#00FFFF'})
      document.getElementById('svg').appendChild(circle);
    }

    // Key Press
    $(document).keydown(function(e) {
      switch(e.which) {
          case 37: // left
            socket.emit('update', 'left');
            break;

          case 38: // up
            socket.emit('update', 'up');
            break;

          case 39: // right
            socket.emit('update', 'right');
            break;

          case 40: // down
            socket.emit('update', 'down');
            break;

          default:
          break;
      }
      e.preventDefault(); // prevent the default action (scroll / move caret)
    });

    socket.emit('update', 'No Keys')

I want the key press even to be sent 5 (about) times a second, not 60-100 like I am experiencing.

Nv7
  • 406
  • 6
  • 20
  • 1
    You will want to use what's called a `debounce`, if your using NPM you could do a search for this. If you are using lodash, it uses this, if you want a non lib version,. There is also one on SO -> https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript/24004942 – Keith May 07 '19 at 21:43
  • How often will the event listener set? Every time you render a frame? –  May 07 '19 at 21:47
  • `60-100` per second? surely you exaggerate, all keyboards I've ever dealt with have a repeat rate at most about 30 or so a second – Jaromanda X May 07 '19 at 21:53
  • I'm not exaggerating, this website runs extremely fast due to a lack of much content, for a second I can get up to 100 FPS – Nv7 May 07 '19 at 21:56
  • This function runs every frame – Nv7 May 07 '19 at 21:57
  • Thank you [keith](https://stackoverflow.com/users/6870228/keith) for answering my question! It works great! – Nv7 May 07 '19 at 22:07

1 Answers1

1

Thanks to keith for answering this question!

The answer was to use the debounce function, which worked extremely well!

Community
  • 1
  • 1
Nv7
  • 406
  • 6
  • 20