ʎɹnɔɹǝW ʎɹnɔɹǝW -4 years ago 113
Javascript Question

Detect time lapse between two key press in Javascript

I am learning javascript and at the same time trying to create a simple script that allows you to type a foreign language on a web browser with your keyboard.

So, when you type

for example, there is a single letter mapped to a, so a single character
would appear, however to make a character like
appear, you have to type twice, since this language has more characters than the English alphabet.

So, the problem is with that last character. Normally, I should have to type
consecutively in the span of one second to produce the
letter, but I have problems waiting to check if within two characters have been typed within one second of eachother inorder to show that letter.

So, I don't think time interval functions are the way to go about this, but I can't see any other method also.

Answer Source

another answer about your question,perhaps this is your truly answer.

 function duration(timestamps) {
        var last = timestamps.pop();
        var durations = [];
        while (timestamps.length) {
            durations.push(last - (last = timestamps.pop()));
        return durations.reverse();

    function display(mills) {
        if (mills > 1000)
            return (mills / 1000) + ' s';
        return mills + ' ms';

    var durations = [];

    $('#in').keydown(function (e) {
    }).keyup(function (e) {
        var current = durations;
        durations = [];
        var timeElapsed = current[current.length - 1] - current[0];

            ['time elapsed:', display(timeElapsed)].join(' '),
            ['keys duration:', duration(current).map(display)].join(' ')
        ].join(' --- '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h2>Please input something to test!</h2>
    <input id="in"/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download