How to speed up this algorithm? In javascript


I have an array of 16 billiard balls in JS and you want to smoothly move each ball in its direction and speed.
To do this, I set the timer, typing UpdateThis()every 42 ms (for 24 frames per second).
The problem is that it UpdateThis()takes 53 ms as firebug states.
Now UpdateThisiterates over each ball and calls UpdateBall(ball).
I guess the problem lies there.
UpdateBall looks like this:

function UpdateBall(ball)
{
if(ball.direction.x != 0 && ball.direction.y != 0) {
    //ball moving!
    for(var i = 0; i < 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 < Bx || ps.y < By || ps.x > Bw || ps.y > 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 < 0.05) {
        ball.speed = 0;
    }
  }
}

It seems that the most time is spent on ball.MoveTo(), which is as follows:

function() 
{
     this.image.style.left = this.position.x + "px";
     this.image.style.top = this.position.y + "px"; 
}


- UPDATE -

function UpdateThis() {
    for(var i = 0; i < balls.length; i++) {
         var cur = balls[i];
         UpdateBall(cur);
         balls[i] = cur;
    }
  }

and onload looks like

nx = setInterval(function() { UpdateThis(); }, 42);

Does anyone have any ideas on how to speed this up?

- UPDATE 2 -

HTML ( - )

+5
3

? - ( ):

function DrawBall(ball)
{
    ball.MoveTo(); //Take this line out of UpdateBall
}

-

function UpdateThis() {
    for(var i = 0; i < balls.length; i++) {
         var cur = balls[i];
         UpdateBall(cur);
         balls[i] = cur;
    }
}

-

function DrawThis() {
    for(var i = 0; i < balls.length; i++) {
         DrawBall(balls[i]);
    }
    setTimeout(function() { DrawThis(); }, 42);
}

-

nx = setInterval(function() { UpdateThis(); }, 42);
setTimeout(function() { DrawThis(); }, 42);

, , , 42 , 42 , . ( , , )

+2

(, , )?

, , . - . , IE9. , , .

, , .:)

  • , ? ? UpdateBall() ? ?

  • VMul VAdd

  • ? , . overflow:hidden . . , . , JSFiddle .

, setInterval , . setInterval , .

, 100%, .

. Firebug, , Javascript Firebug.

+2

, MoveTo() , . , , ,

1) . , , . MoveTo().

2) 'px'? CSS, . , 2 , .

, , , , DOM, . , , . 2 (1 , 1 ) 2 .

EDIT: № 1 , , . , . :

var Ball = function(img){
    var style = img.style;
    var posX;
    var posY;

    function MoveTo(){
        style.left = posX + "px";
        style.right = posY + "px"; 
    }
};
+1

All Articles