1

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');
   }
}
Dmitry Chernyak
  • 295
  • 3
  • 12
  • `shows a completely different time`...give an example: what time did you expect? What time did you actually get? – ADyson Jul 13 '22 at 16:51
  • `if (event.repeat) return;` in `onkeydown` – skara9 Jul 13 '22 at 17:03
  • Does this answer your question? [Prevent JavaScript keydown event from being handled multiple times while held down](https://stackoverflow.com/questions/6087959/prevent-javascript-keydown-event-from-being-handled-multiple-times-while-held-do) – skara9 Jul 13 '22 at 17:03
  • use this condition in both function keydown and keyup `key === 'Delete' || key === 'Backspace'` – Mohit Sharma Jul 13 '22 at 17:04
  • @ADyson I had i time less than 1 second every time. Maybe it was i time pressing button – Dmitry Chernyak Jul 13 '22 at 17:28

1 Answers1

1

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]
IT goldman
  • 14,885
  • 2
  • 14
  • 28