Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
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');
   }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!