2

I have the following code:

undoButton.onclick = undoFunction; document.addEventListener("keydown", (e) => { if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") { e.preventDefault(); undoFunction(); } }); function undoFunction() { console.log("undo function..."); } 

When I click the button, as excepted, the function code runs once, and so does the console.log, but when I use the key stroke, the function is running a multiple times, up to hundreds of so-called loops at some scenarios. Any suggestion why? I tried to used e.repeat = false but had no luck. Thanks!

5
  • 4
    What is the context for the code you posted? It's important to understand that .addEventListener() does just that: it adds an event listener, without removing any previously-added event listeners. If you do that over and over again, all of the added event listeners will run on every "keydown" event. Commented Mar 10, 2022 at 19:36
  • What you are looking for is debouncing: freecodecamp.org/news/javascript-debounce-example Commented Mar 10, 2022 at 19:36
  • @mashuptwice Not needed here at all Commented Mar 10, 2022 at 19:40
  • The keydown event triggers multiple times while you're holding down the button because your keyboard sends the key multiple times. Just like holding a keyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy here in the text field. Commented Mar 10, 2022 at 19:42
  • Try using keyup or keypressed instead Commented Mar 10, 2022 at 19:44

1 Answer 1

1

Use keyup instead. The keydown event triggers as long a key is hold down. keyup only triggers when a key is released.

var undoButton = document.getElementById('undoButton'); undoButton.onclick = undoFunction; document.addEventListener("keyup", (e) => { if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") { e.preventDefault(); undoFunction(); } }); function undoFunction() { console.log("undo function..."); }
<input id="undoButton" type="button" value="Undo" />

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.