Key Hold Duration with keydown and keyup

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.

Press and hold any key.
Duration will appear here after release.

jQuery Source Top ↑

$( 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 = "";
        }
    });
});

Why Check the First keydown Top ↑

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.

Video Tutorial on Keyboard Events






plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer