user695868
user695868

Reputation:

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; } 
});

Upvotes: 0

Views: 635

Answers (2)

PRB
PRB

Reputation: 484

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?

Upvotes: 2

adeneo
adeneo

Reputation: 318182

var timer;

$(document).on('keydown', function (e) {
   clearTimeout(timer);

   timer = setTimeout(function() {
       if ($(e.target).is('input')) { 
           e.stopPropogation(); 
       }else if (e.keyCode == 37) { 
           e.preventDefault();
           $(".pageback").click(); 
       }

       if (e.keyCode == 39) { 
           e.preventDefault();
           $(".pagenext").click();
       } 
   }, 200);
});

Use a simple timeout that clears when a key is pressed, that way the function won't execute if the user is typing faster than one key every 200ms.

Upvotes: 0

Related Questions