Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop forever and provide delta time

I'm writing an HTML5 Game Development Javascript framework and I want to provide the user the difference in time between the last tick and the current one.

setInterval(tick, 16.6666666);

function tick() {
  update();
  draw();
}

That's what I have, but I want to have:

while (true) {
  /* Calculate delta time */

  tick(dt);
}

function tick(dt) {
  update(dt);
  draw();
}

I tried that, using date.getTime(); to calculate delta time, but Firefox said the script crashed. Obviously, an infinite loop will crash. Got any suggestions for how I can go about this?

I want an infinite loop, that can be stopped with break. I want to pass delta time too, but that I know how to do.

like image 516
David Gomes Avatar asked Dec 21 '12 19:12

David Gomes


People also ask

How is Delta time calculated?

It is done by calling a timer every frame per second that holds the time between now and last call in milliseconds. Thereafter the resulting number (delta time) is used to calculate how far, for instance, a video game character would have travelled during that time.

What is Delta time in Javascript?

The system variable deltaTime contains the time difference between the beginning of the previous frame and the beginning of the current frame in milliseconds. This variable is useful for creating time sensitive animation or physics calculation that should stay constant regardless of frame rate.

What is a Delta second?

Delta time describes the time difference between the previous frame that was drawn and the current frame. Note: A frame refers to the image we see on the screen, which gets updated a certain number of times a second.


2 Answers

Just maintain a variable with the time of the last update, and calculate the elapsed time/delta time in tick itself.

var lastUpdate = Date.now();
var myInterval = setInterval(tick, 0);

function tick() {
    var now = Date.now();
    var dt = now - lastUpdate;
    lastUpdate = now;

    update(dt);
    render(dt);
}

Here's a JSBin, though I don't think it's really needed... http://jsbin.com/okimam/10

EDIT: I must point out that setInterval(tick, 0) does not necessarily mean that tick will be called immediately, with an interval of '0ms' between two calls. It depends on the browser.

like image 76
Rikonator Avatar answered Sep 21 '22 09:09

Rikonator


This is what I use:

let lastTick = performance.now()

function tick(nowish) {
  const delta = nowish - lastTick
  lastTick = nowish

  update(delta)
  render(delta)

  window.requestAnimationFrame(tick)
}

window.requestAnimationFrame(tick)
like image 30
Chris Buck Avatar answered Sep 23 '22 09:09

Chris Buck