عدّ ضغطات مفتاح المسافة في 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 يجعلان الضغطة الفعلية الواحدة تضيف واحدًا بالضبط إلى العدد.