So i my previous thread i had a button but that button has been replaced with a key for now. E.g Spacebar. What i wanted to do there is hide the button for 5 seconds. But that did not work out so far. My question is: How to avoid a person pressing the spacebar twice in 5 seconds? For example: Player presses spacebar and a interval will run that lasts 5 seconds. Pressing space again will glitch out really bad. So how do i disable a function for 5 seconds after it has been called? This is my code: <script> document.body.onkeyup = function(e){ if(e.keyCode == 32){ // Pressing spacebar should only be able to call once each 5 secs. var cmd = "<?php echo $row['HEADING']; ?>"; if(cmd == "N") myMoveUp(); if(cmd == "E") myMoveRight(); if(cmd == "S") myMoveDown(); if(cmd == "W") myMoveLeft(); } if(e.keyCode == 37){ ChangeHeadingKP("W"); } if(e.keyCode == 38){ ChangeHeadingKP("N"); } if(e.keyCode == 39){ ChangeHeadingKP("E"); } if(e.keyCode == 40){ ChangeHeadingKP("S"); } } </script> Code (markup):
Ask the question on https://stackoverflow.com DP has good coders but they may not always be on here. On stackoverflow you'll get your solution within 10 minutes.
Have a variable with the time of the last space key hit and ignore any that happen until the 5 seconds is up
Thanks for your reply sarahk. I did try that but somehow somewhere it didn't work. On stackoverflow someone came up with a pretty neat solution if anyone may be interested: keymanager.suspend(); // play animation, cutscene or whatever keymanager.resume(); //Those two functions are easy to define, along with the keymanager, as follows: var keymanager = { "active": true, "suspend": () => { keymanager.active = false; }, "resume": () => { keymanager.active = true; } }; //All that remains is the key event handler bailing out when keys are deactivated: document.body.onkeyup = function (e) { if (!keymanager.active) { return; // do not process any keys } // rest of your code... } Code (markup):