Nina
Nina

Reputation: 23

Calculate how long a key is pressed in a keyboard

is it possible to have to use two keys for example and it will accumulate the time pressed for each key, for example key LEFT and RIGHT, so every time you click on one of them it will accumulate the time it has been pressed for, in case you press the same key again, it will add the time so at the end you get total time pressed for each key.

How can this be done?

Upvotes: 1

Views: 3373

Answers (1)

cHao
cHao

Reputation: 86506

Depends quite a bit on the platform. But event-driven platforms have it kinda easy, if they treat key-down and key-up as events (most do, including .net, java, and Windows).

Just listen for the key-down event, and record the time it happened. When you get a key-up event for that same key, just subtract the time it happened from the time you recorded. The difference between the two will be the duration of that keypress.

Catch is, depending on how your platform handles key repeat, you may get multiple key-downs for the same key before you get a key-up. Only keep track of the first (since the last key-up or app start, of course) for each key. And since you can press more than one key at a time, if you want to do this right, you'll be able to remember the key-down time for multiple keys.

If you want to keep track of the total time, then take that time difference you found on key-up, and add it to a running total for that key.

In JS:

(function() {
    var output = document.getElementById('output'),
        totalTime = {},
        pressed = {};

    window.onkeydown = function(e) {
        if (e.which in pressed) return;
        pressed[e.which] = e.timeStamp;
    };

    window.onkeyup = function(e) {
        if (!(e.which in pressed)) return;
        var duration = ( e.timeStamp - pressed[e.which] ) / 1000;
        if (!(e.which in totalTime)) totalTime[e.which] = 0;
        totalTime[e.which] += duration;
        output.innerHTML +=
            '<p>Key ' + e.which + ' was pressed for ' +
            duration + ' seconds this time' +
            '(' + totalTime[e.which] + ' total)</p>';
        delete pressed[e.which];
    };
})();

Upvotes: 3

Related Questions