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.
This is what I use:
var lastTick = performance.now()
function tick(nowish) {
var delta = nowish - lastTick
lastTick = nowish
update(delta)
render(delta)
window.requestAnimationFrame(lastTick)
}
window.requestAnimationFrame(lastTick)
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.
Are you over thinking it?
var myInterval = window.setInterval(calculateForDeltaHere , 20);
function calculateForDeltaHere () {
/* Calculate delta time */
dt = Math.random();
tick(dt);
}
function tick() {
update();
draw();
}
And when you want to stop the interval
window.clearInterval(myInterval);
Would like to give my two cents. Usually I use this deltatime method in my games:
const perfectFrameTime = 1000 / 60;
let deltaTime = 0;
let lastTimestamp = 0;
function start() {
requestAnimationFrame(update);
}
function update(timestamp) {
requestAnimationFrame(update);
deltaTime = (timestamp - lastTimestamp) / perfectFrameTime;
lastTimestamp = timestamp;
// YOUR FRAME CODE HERE!
}
start();
This ensure you will have perfect deltatime (as like Unity deltaTime) so you can scale your times to frame time.