带有时间限制的Javascript按键事件

时间:2014-04-08 10:42:20

标签: javascript keypress time-limiting

所以我的问题是使用函数keydown进行多重键,我需要应用时间限制,当你按键等待5秒然后你可以再次按下键。我怎样才能做到这一点?例如:

$(document).keydown(function (e) {
            var keyCode = e.keyCode || e.which,
                arrow = {left: 37, up: 38, right: 39, down: 40 };
                if(keyCode == arrow.left) {
                    ex1();
                } else if (keyCode ==arrow.right) {
                    ex2();  
                } else if (keyCode == arrow.up) {
                    ex3();  
                } else if(keyCode == arrow.down) {
                    ex4();  
                }

});

1 个答案:

答案 0 :(得分:0)

这是实现这一目标的一种非常简单的方法(如果我理解正确的话)

$(function() {
  var pressed = false; //Global var to hold state

  $(document).keydown(function (e) {

      if( pressed === true ) { //Already pressed don't allow another press
         alert("Please wait 5 seconds between key presses");
         return false;
      }

      pressed = true;
      setTimeout(function() { pressed = false }, 5000);

      var keyCode = e.keyCode || e.which;
      var arrow = {left: 37, up: 38, right: 39, down: 40 };              
      if(keyCode == arrow.left) {
         ex1();
      } else if (keyCode ==arrow.right) {
         ex2();  
      } else if (keyCode == arrow.up) {
         ex3();  
      } else if(keyCode == arrow.down) {
         ex4();  
      }
  });
});

设置一个简单变量来保持按下状态(true或false)。如果按下为true,则返回false,以便不发生任何功能。否则让他们按下按钮。将press设置为true并设置5秒超时以将状态恢复为false。