Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check key press multiple times in js?

I’m trying to create a cubing timer. When I press & hold Space, timer should become green. When I release, timer should start running. When I press again, timer should stop. And then all of this should happen again.

I need to check if:

  1. Space bar was pressed.
  2. Space bar was released.
  3. Space bar was pressed again.

I have this code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var down = false;
document.addEventListener('keydown', function () {
    if (event.code === 'Space') {
        if(down) return;
        down = true;
        console.log('Waiting...')
    }
}, false);

document.addEventListener('keyup', function () {
    if (event.code === 'Space') {
        down = false;
        console.log('Start')
    }
}, false);

// I need some Stop function here

The problem is that when I press space bar and then release it and press again, it runs 4 functions. But I need to run 3 different ones. And then I have to be able to do the same again.

How can I do this?

>Solution :

You could use KeyboardEvent::repeat to check whether you have the first key down event:

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat

Also note that window.event is deprecated:

https://developer.mozilla.org/en-US/docs/Web/API/Window/event

So the logic is to use a finite state automata and switch between states on key presses, so call you logic instead of console.log() based on the current state:

let state = 'stopped';

document.addEventListener('keydown', changeState);
document.addEventListener('keyup', changeState);

function changeState({code, repeat, type}){

  if(code !== 'Space' || repeat){
    return;
  }

  if(type === 'keydown'){
    state = state === 'stopped' ? 'waiting' : 'stopped';
  } else if(type === 'keyup'){
    if(state === 'stopped'){
      return;
    }
    state = 'started';
  }
  
  console.log(state);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading