title: Making A Game in Javascript, Wondering why my object speeds up every-time I press the left or right arrow button
body: <p>It is just the beginning process of the game, but I am wondering why my rectangle speeds up every time I press the left or right arrow button. I just want to make is move a little and stop when the buttons are released and have the same speed every-time.</p>
  <pre><code>    &lt;body&gt;
      &lt;canvas height=&quot;400&quot; width=&quot;400&quot; id=&quot;myCanvas&quot;&gt;&lt;/canvas&gt;       
      &lt;script&gt;
          &quot;use strict&quot;
          var a=document.getElementById(&quot;myCanvas&quot;);
          var c=a.getContext(&quot;2d&quot;);
          var shipX=180;
          var speed=1;
          c.fillStyle=&quot;white&quot;;
          c.beginPath();
          c.rect(shipX,350,40,30);
          c.fill();
          c.closePath();
          
          window.onkeydown=function(e){
              if(e.keyCode==37){
                   speed=-1;
                   window.setInterval(moveShip,17);
              }
              if(e.keyCode==39){
                  speed=1;
                  window.setInterval(moveShip,17);
              }
          }
          
          window.onkeyup=function(e){
              if(e.keyCode==37){
                  speed=0;
              }
              if(e.keyCode==39){
                  speed=0;
              }
          }
          
          
          function moveShip(){
              shipX+=speed; 
              c.clearRect(0,350,400,50);
              c.fillStyle=&quot;white&quot;;
              c.beginPath();
              c.rect(shipX,350,40,30);
              c.fill();
              c.closePath();
      }
          
      &lt;/script&gt;
  &lt;/body&gt;
  </code></pre>