开发者

Javascript on second keypress

开发者 https://www.devze.com 2022-12-16 23:58 出处:网络
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.

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 (es开发者_运维知识库capeCount == 2) {
     // stuff on second escape
   }
 };

Is there a better way to do this? Thanks


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号