views:

225

answers:

2

Hi

I've been wondering if there was a simple way to detect if a user presses the same character on the keyboard twice within one second. I've written some code that kind of works but it's unreliable.

var escapeCount = 0;

 function reset() {
   escapeCount = 0;
   setTimeout('reset();', 1000);
 }

 window.onload = function() {
   reset();
 };

 document.onkeyup = function(e) {
   if (!e) var e = window.event;
   var code = e.keyCode ? e.keyCode : e.which;
   if (code == 27) escapeCount +=1;
   if (escapeCount == 2) {
     // stuff on second escape
   }
 };

Is there a better way to do this? Thanks

+3  A: 

It would make sense to reset after 1 second has passed since the last character was pressed. Example:

var lastChar = -1;

document.onkeyup = function(e) {
  if (!e) var e = window.event;
  var code = e.keyCode ? e.keyCode : e.which;

  if (lastChar == code) {
    // Same key was pressed twice in a row within 1 second.
  } else {
    lastChar = code;
    setTimeout(function() {lastChar = -1;}, 1000);
  }
};
Max Shawabkeh
works like a dream!
Declan Haigh
A: 

Your timer resets every second, so you not only have to press Escape again within a second of the last Escape, but that also has to have no timeout in between the presses.

It's probably easier to forget the timeout and just remember the time of the last keypress instead:

var lastescapetime= null;

document.onkeyup= function(event) {
    if (event===undefined) event= window.event;
    if (event.keyCode===27) {
        var now= new Date().getTime();
        if (lastescapetime!==null && now<lastescapetime+1000) {
            alert('You double-escaped!');
            lastescapetime= null;
        } else {
            lastescapetime= now;
        }
    } else {
        lastescapetime= null;
    }
};
bobince