So my problem is multipressing key with function keydown and i need to apply time limit, when u hit key wait 5 sec and then you can again hit the key. How can i do this? example:

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

});
有帮助吗?

解决方案

This is a very simple way to achieve this (If i've understood you correctly)

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

Set a simple variable to hold the pressed state (true or false). If pressed is true return false so that no functionality happens Else let them press the button. set pressed to true and set a 5 second timeout to return the state back to false.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top