Search code examples
jquerydelaykeydown

delay another key press after initial press for XXX ms


I'm struggling with finding a way to add a short 200 ms delay after a keydown event.

This is to prevent someone from pressing the keys too fast one right after the other.

Here is the code currently:

$(document).keydown(function (e) {
   if ($(e.target).is('input')) { e.stopPropogation(); }
   else if (e.keyCode == 37) { $(".pageback").click(); return false; }
   if (e.keyCode == 39) { $(".pagenext").click(); return false; } 
});

Solution

  • You can't prevent someone from pressing the key too quickly, and it's probably unwise/impossible to stop the message from coming. however, you can track the time since the last key press and ignore the message if it's too soon:

    var last_time = null;
    $(document).keydown( function (e) {
        var now = new Date().getTime(),
            diff;
        if ($(e.target).is('input')) { 
            e.stopPropogation(); 
        } else if (e.keyCode == 37 || e.keyCode == 39) { 
            if( last_time != null ) {
                diff = now - last_time;
                if( diff < 200 ) {
                    return false;   // do nothing
                }
            }
            last_time = now;
            if (e.keyCode == 39) { 
                $(".pageback").click(); 
                return false; 
            } if (e.keyCode == 39) { 
                $(".pagenext").click(); 
                return false;
            } 
        } 
    });
    

    Each time a key is pressed, the time since the last successful press is checked and if there has been enough delay, record the current time and carry on. Otherwise, drop out.

    Make sense?