Press a key, keep it held for a moment, and then release it. This example measures the time between the first keydown and the matching keyup.
$( function () {
let startTime = 0;
let activeCode = "";
$( document ).on( "keydown", function (event) {
if ( startTime === 0 ) {
startTime = performance.now();
activeCode = event.code;
$( "#d1" ).text(
"Holding: " + event.key + " (" + event.code + ")"
);
}
});
$( document ).on( "keyup", function (event) {
if ( startTime !== 0 && event.code === activeCode ) {
const duration = performance.now() - startTime;
$( "#d2" ).text(
"Released: " + event.key +
" | Held for: " + duration.toFixed( 0 ) + " ms"
);
startTime = 0;
activeCode = "";
}
});
});
When a key is held, browsers can generate repeated keydown events. The example records the start time only once, then waits for the matching keyup.
keydown() starts the measurement and keyup() ends it. The keypress page is retained as a legacy reference. See modern key identification for event.key and event.code.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.