Search code examples
javascriptdelaygame-enginekeyboard-eventsonkeydown

Moving elements is delayed when I'm using the onKeyDown event


I am trying to make an element move when I hold down a key (left or right arrow in this case), but when I hold down a key the movement is delayed by about a second. Am I using the wrong event or is there anything wrong with my code?

I am using the onKeyDown event to trigger the movement.

<head>
<script>
	var objX = 100;		
	function blockMove(e){
		if (e.keyCode == 37) { //move left
			objX-=4;
			document.getElementById("object").style.left = objX + "px";	
		} else if (e.keyCode ==  39) { //move right
			objX+=4;
			document.getElementById("object").style.left = objX + "px";	
		}
	}			
	</script>
</head>
<body onkeydown="blockMove(event)">
	<div id=object style="height:10px;width:80px;background-color:red;position:absolute;top:50px;left:100px"></div>
</body>


Solution

  • Bear with me, this is kind of long and possibly buggy: (also a spoiler if you want to do it yourself)

    <head>
    <script>
        var objX = 100;     
       var leftDown = false;
       var rightDown = false;
            function blockMove(e){
                if(e.keyCode == 37 && !leftDown) { //move left
                leftDown = true;
                    objX-=4;
                    document.getElementById("object").style.left = objX + "px"; 
                    }else if(e.keyCode ==  39 && !rightDown) { //move right
                   rightDown = true;
                        objX+=4;
                        document.getElementById("object").style.left = objX + "px"; 
            }}
          function stopMove(e)
          {
             if( e.keyCode == 37 )
                leftDown = false;
             if( e.keyCode == 39 )
                rightDown = false;
          }
           function timer()
          {
             if( leftDown )
                objX -= 4;
             if( rightDown )
                objX += 4;
             document.getElementById("object").style.left = objX + "px";    
          }
          setInterval(timer, 100);
        </script>
    </head>
    <body onkeydown="blockMove(event)" onkeyup="stopMove(event)">
        <div id=object 
    style="height:10px;width:80px;background-color:red;position:absolute;top:360px;left:100px"
        ></div>
    </body>