Count spacebar presses in JavaScript
let count = 0;let down = false;
document.addEventListener('keydown', (event) => { if (event.code !== 'Space') return; event.preventDefault(); // keep the page from scrolling if (event.repeat || down) return; // a held key counts once down = true; count += 1; console.log(count);});
document.addEventListener('keyup', (event) => { if (event.code === 'Space') down = false;});This is the core of the test. The keydown event fires when the key goes down and keeps firing while it is held, with event.repeat set to true. Skipping repeats and waiting for keyup means one physical press adds exactly one to the count.