Search code examples
javascriptonkeydownfunction-call

Only be able to press space once every half a sec


When i press spacebar, the function shoot executes.

window.onkeydown=function(e){
    var which = e.keyCode;
    if(which == 32){
        shoot();
    }
}

If you hold space down, shoot calls many times in a row. I only want the function to execute once every 500ms.


Solution

  • (function($){
    
        var lazerCharging = false,
            lazerChargeTime = 500;  // Charge time in ms
    
        function handleKeyPress(e){
            if(e.keyCode == 32){
                shoot(lazerChargeTime);   
            }
        }
    
        function shoot(chargeTime){
    
            if(!lazerCharging){        
    
                lazerCharging = true;       
                $("body").append("pew<br/>");
    
                setTimeout(function(){
                    lazerCharging = false;
                }, chargeTime)            
            }        
        }
    
        $(window).on("keydown", handleKeyPress);
    
    })($);
    

    Here's a jsfiddle