简体   繁体   中英

How to track the time of the pressed button? JavaScript

I need your help. With the help of the following code, I am trying to detect the time that the Delete key was pressed. My code doesn't give me any errors, but it doesn't work quite right. For example, if I press the key for 3 seconds, it shows a completely different time than it should. Tell me what I am doing wrong, what is my mistake? Thank you very much?)

var startTime;

document.body.onkeydown = function() {
   const key = event.key;
   if (key === 'Delete') {
      console.log('key down');
      startTime = +new Date();
   }
}

document.body.onkeyup = function() {
   const key = event.key;
   if (key === 'Delete') {
     console.log('key up')
     var endTime = +new Date();
     var time = (endTime - startTime) / 1000;
     if (time > 3) {
        console.log('cool')
     }
    console.log(time + ' sec');
   }
}

You can ignore multiple repetitions using a little flag you set up.

 var startTime; var delete_down = false; document.body.onkeydown = function(ev) { const key = event.key; if (key === 'Delete') { ev.preventDefault(); if (delete_down) { return } delete_down = true; console.log('key down'); startTime = +new Date(); } } document.body.onkeyup = function() { const key = event.key; if (key === 'Delete') { console.log('key up') delete_down = false; var endTime = +new Date(); var time = (endTime - startTime) / 1000; if (time > 3) { console.log('cool') } console.log(time + ' sec'); } }
 click me then hit [Del]

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