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:
- Space bar was pressed.
- Space bar was released.
- Space bar was pressed again.
I have this code:
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);
}