Dmitry Chernyak
Dmitry Chernyak

Reputation: 305

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');
   }
}

Upvotes: 0

Views: 676

Answers (1)

IT goldman
IT goldman

Reputation: 19493

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]

Upvotes: 1

Related Questions