• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

262
Views
How can I disable repetition of an eventListener keydown event in plain JavaScript

I am trying to stop a keydown event from repeating for a game. I am unable to use libraries due to it being part of a school project. I have tried most of the answers I can access but they don't work for my code, I also can't use MDN because it's blocked. Here is the code

     window.addEventListener("keydown", function (e){
      if (e.keyCode == 32) {
       accelerateBy = -0.5
       accelerate()
      
     }
    });
about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You may have to use some variable to save the state of you key. Here's an example:

let isKeyDown = false;

document.addEventListener("keydown", (event) => {
    if (event.keyCode == 32) {
        if (isKeyDown) { return; } // If key was already down, don't do anything
        isKeyDown = true;
        // do your stuff here
    }
});

document.addEventListener("keyup", (event) => {
    if (event.keyCode == 32) {
        isKeyDown = false;
    }
});
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error