title: How to speed up this moving algorithm? In Javascript
body: <p><br>I have an Array of 16 billiard balls in JS and want to move each ball smoothly with its direction and speed.<br>
  For that I set up a timer, calling <code>UpdateThis()</code> every 42ms (for 24 fps).<br>
  The problem is that <code>UpdateThis()</code> takes 53ms as firebug states.
  <br>Now <code>UpdateThis</code> iterates over every ball and calls <code>UpdateBall(ball)</code>.<br>
  I assume that the problem lies there.<br>UpdateBall looks like this:</p>
  
  <pre><code>function UpdateBall(ball)
  {
  if(ball.direction.x != 0 &amp;&amp; ball.direction.y != 0) {
      //ball moving!
      for(var i = 0; i &lt; balls.length; i++) {
          //CheckCollision(ball, balls[i]); //even without this it takes 53 ms!
      }
  
      var ps = VAdd(ball.position, VMul(ball.direction, ball.speed)); //Multiply Direction with speed and add to position!
      if(ps.x &lt; Bx || ps.y &lt; By || ps.x &gt; Bw || ps.y &gt; Bh) { //Bounce off the wall!
          ball.direction = VMul(ball.direction, -1); //Invert direction
          ball.speed *= 1;
          ps = VAdd(ball.position, VMul(ball.direction, ball.speed)); //Calc new position!
      }
      ball.position = ps;
      ball.MoveTo(); //See explanation at the bottom.
      ball.speed *= GRK; //Gravity
      if(ball.speed &lt; 0.05) {
          ball.speed = 0;
      }
    }
  }
  </code></pre>
  
  <p>it seems that the most time is spent in <code>ball.MoveTo()</code> which looks like this:</p>
  
  <pre><code>function() 
  {
       this.image.style.left = this.position.x + "px";
       this.image.style.top = this.position.y + "px"; 
  }
  </code></pre>
  
  <p><br>
  -- UPDATE --</p>
  
  <pre><code>function UpdateThis() {
      for(var i = 0; i &lt; balls.length; i++) {
           var cur = balls[i];
           UpdateBall(cur);
           balls[i] = cur;
      }
    }
  </code></pre>
  
  <p>and onload looks like </p>
  
  <pre><code>nx = setInterval(function() { UpdateThis(); }, 42);
  </code></pre>
  
  <p>Does somebody have any ideas on how to speed this up?
  <br><br>-- UPDATE 2 --</p>
  
  <p>You can download the folder with the HTML file <a href="http://www.mediafire.com/?fl6i8uaaehtskko" rel="nofollow">here</a> (the password is password)</p>