Reputation: 55
I have written an animation to recreate elastic collisions between balls. I move the balls every >10ms. The problem is, when I load the animation, there is an initial lag. I am not doing anything repetitive/intensive at the beginning of my code, though. Even when I reduce the ball count to something like 5 balls the problem persists. Could the method I am using for repetition be flawed?
function moveBalls() {
for(j = 0; j < ball_count; j++) {
balls[j].move();
}
setTimeout(moveBalls, 10);
}
This is the main loop. Perhaps this is the culprit. Is there a more reliable way to run the function at an interval? Any help is greatly appreciated.
Upvotes: 0
Views: 48
Reputation: 8732
Yes, there is a better way to run that function - this is what a lot of HTML5 games use:
Window.requestAnimationFrame()
This tells the browser that you're doing an animation and want to run the function again ASAP. It will run it the next time it paints the screen.
This is faster and overall makes for a higher framerate, as well as performance (as setTimeout
is not very accurate).
Article here (MDN).
Upvotes: 2