John Smith
John Smith

Reputation: 13

Javascript on second keypress

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

Upvotes: 1

Views: 1490

Answers (2)

bobince
bobince

Reputation: 536359

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

Upvotes: 0

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

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

Upvotes: 5

Related Questions