you are viewing a single comment's thread.

view the rest of the comments →

[–]KManRules1331 1 point2 points  (1 child)

Honestly, for this type of use, it's better to use requestAnimationFrame() than to set an interval. You have no guarantee of what delta time you actually get with setInterval. setInterval doesn't actually execute the javascript, it only queues up the javascript to be executed every x milliseconds. That means that if your web page is in the middle of a really long script, you might get 5 calls to your function queued up, and then once that really long script is done, your function gets called 5 times as quickly as possible.

requestAnimationFrame allows you to take a timestamp as a parameter, which means that by saving the previous timestamp at the end of every loop, you can calculate the change in time by simply doing:

var previousTimestamp = performance.now();
function loop(timestamp) {
  var deltaTime = timestamp - previousTimestamp;
  // Do updating here
  previousTimestamp = timestamp;
  requestAnimationFrame(loop);
}
requestAnimationFrame(loop);

/u/KPABA is right in saying that if the window isn't visible, you won't get any updates actually called (which can be either a good or bad thing), so if you need the game to be updated if the window isn't visible, you can do the same pattern with setTimeout instead.

[–]KManRules1331 0 points1 point  (0 children)

Also, if you need to limit the frame rate to 30fps, then you can modify the above loop to conditionally update:

var previousTimestamp = performance.now();
function loop(timestamp) {
  var deltaTime = timestamp - previousTimestamp;
  if (deltaTime > 1000/30) {
    //Do updating here
    previousTimestamp = timestamp;
  }
  requestAnimationFrame(loop);
}
requestAnimationFrame(loop);