简体   繁体   中英

How to get the correct timing of a key being released (JS' keyup is not accurate)?

When I use keyup I never get a timestamp later then about keydown+500ms even if I hold down the key much longer. I'm using

 document.addEventListener('keyup', function(event) {
 if (event.code == 'KeyZ' )
  {
    var d = new Date();var time = d.getTime();
  }
 });

This is because the keydown will be fired multiple times when the key is held down. Try placing a console.log in the keydown event handler and you'll see.

This behaviour is not consistent between browsers and operating systems. For a detailed list of behaviours, check out http://unixpapa.com/js/key.html .

The timing between each keydown event when a key is held down can even be configured on Windows computers and possibly on other operating systems too. See https://answers.microsoft.com/en-us/windows/forum/windows_xp-performance/can-you-disable-the-keyboard-autorepeat-function/ce1b29bc-544b-e011-8dfc-68b599b31bf5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM