Monday, May 4, 2015

javascript - What is better for the overall performance and feel of the game: one setInterval performing all the work, or many of them doing individual tasks?


This question is, I suppose, not limited to Javascript, but it is the language I use to create my game, so I'll use it as an example.


For now, I have structured my HTML5 game like this:


var fps = 60;
var game = new Game();

setInterval(game.update, 1000/fps);


And game.update looks like this:


this.update = function()
{
this.parseInput();
this.logic();
this.physics();
this.draw();
}


This seems a bit inefficient, maybe I don't need to do all of those things at once. An obvious alternative would be to have more intervals performing individual tasks, but is it worth it?


var fps = 60;
var game = new Game();

setInterval(game.draw, 1000/fps);
setInterval(game.physics, 1000/a); //where "a" is some constant, performing the same function as "fps"
...

With which approach should I go and why? Is there a better alternative? Also, in case the second approach is the best, how frequently should I perform the tasks?



Answer




A single task is definitely better.


You don't want nondeterministic behaviour.


While Javascript normally runs all your code in one thread and won't interrupt it (it will not preempt other JS code), there's no guarantee of how often, or in what order or proportion, several timers will really run. If one timer event is a bit slow, others might get skipped.


In general, you probably want to be using requestAnimationFrame for rendering, and doing your game logic however often suits you.


I use a fixed timestep with interpolation, because that way I get deterministic behaviour. I trigger it all from requestAnimationFrame, and look at the clock to see if enough time has passed to run another game-logic "tick".


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...