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;});これがテストの中心です。keydown イベントはキーが下がったときに発生し、押し続けているあいだは event.repeat が true の状態で発生し続けます。繰り返しを飛ばして keyup を待つことで、実際の1回がちょうど1としてカウントされます。