Search code examples
javascriptjqueryrecordtimingkeystroke

Javascript record keystroke timings


I want to record the time between each keystroke (just one key to start with, the 'A' key) in millseconds. After the user finishes his thing he can submit and check out the timings between each key stroke. Like:

1: 500 2: 300 3: 400 4: 500 5: 100 6: 50 7: 50 8: 25

I believe this is possible with Javascript, is it?


Solution

  • Sure:

    var times = [];
    
    // add an object with keycode and timestamp
    $(document).keyup(function(evt) {
        times.push({"timestamp":evt.timeStamp,
                    "keycode":evt.which})
    });
    
    // call this to get the string
    function reportTimes() {
        var reportString = "";
        for(var i = 0; i < times.length - 1; ++i) {
             reportString += (i+1) + ": " + (times[i+1].timestamp - times[i].timestamp) + " ";
        }
        return reportString; // add this somewhere or alert it
    }
    

    I added the keycode just in case you wanted it later; it's not necessary for your exact problem statement.


    Clarification from comments discussion:

    The for loop only goes to up to times.length - 2 (since i is always strictly less than times.length - 1), so there is no issue about times[i+1] being outside the bounds of the array. For example, if you do five key presses and therefore have a times array with five elements (indexed from 0 to 4):

    1st pass: times[1].timestamp - times[0].timestamp
    2nd pass: times[2].timestamp - times[1].timestamp
    3rd pass: times[3].timestamp - times[2].timestamp
    4th pass: times[4].timestamp - times[3].timestamp
    

    Then the loop terminates, because setting i to 4 triggers the termination condition:

    = i < times.length - 1
    = 4 < 5 - 1
    = 4 < 4
    = false  [i cannot be set to 4 by this loop]
    

    Thus, times[i+1] is always a validly indexed element, because i is at most one less than the maximum index.