Differentiate between key pressed and key held

Tom picture Tom · Aug 23, 2011 · Viewed 7.4k times · Source

I have a javascript function which runs when the 'down' key is pressed. I would like, that if the 'down' key is held down, the function would not run at all.

I thought about timing between keydown and keyup, if the time is less than 1 second then the function would run on keyup. The problem is, if I hold the key down the browser sees it as the key being pressed many times in succession.

Is there a better way to do this?

Thanks

Answer

Brent Stradling picture Brent Stradling · Jul 19, 2018

There is a keyboard event property called repeat that returns true if the key is being held down.

document.addEventListener('keydown', (event) => {
  if(event.repeat) {
    // key is being held down
  } else {
    // key is being pressed
  }
});