title: Simple Javascript loop that repeats each second
body: <p>I'm writing a code to move a character in a browser game. I managed to get the pixels it must move per second both horizontally and vertically.</p>
  
  <p>pxsecx is the number of pixels it must move horizontally per second
  pxsecy is the same but vertically</p>
  
  <p>Basically it should += them to the current horizontal and vertical position.</p>
  
  <p>I need the loop to keep repeating itself every second until the element position meets the new position (newx). </p>
  
  <p>This is as far as I have gone:</p>
  
  <pre><code>&lt;body onmousedown="showCoords(event)"&gt;
  &lt;script type="text/javascript"&gt;
  function showCoords(evt){
    oldx = parseInt(document.getElementById("character").style.left);
    oldy = parseInt(document.getElementById("character").style.top);
  
    width = parseInt(document.getElementById("character").style.width);
    height = parseInt(document.getElementById("character").style.height);
  
    newx = evt.pageX - width/2;
    newy = evt.pageY - height/2;
  
    disx = newx - oldx;
    disy = newy - oldy;
  
    diag = parseInt(Math.sqrt(disx*disx + disy*disy));
  
    speed = 50;
  
    secs = diag/speed;
  
    pxsecx = disx/secs;
    pxsecy = disy/secs;
  
       while(document.getElementById("character").style.left&lt;newx)
        {
        document.getElementById("character").style.left += pxsecx;
        document.getElementById("character").style.top += pxsecy;
        }
  }
  &lt;/script&gt;
  </code></pre>
  
  <p>Everything works until the while where I have no idea how to do make it work every second. I'm testing it here: <a href="http://chusmix.com/game/movechar.php" rel="noreferrer">http://chusmix.com/game/movechar.php</a></p>
  
  <p>How do I make it repeat that once a second so it works?</p>
  
  <p>thanks</p>