Skip to content

Instantly share code, notes, and snippets.

@ahvonenj
Last active October 9, 2018 13:24
Show Gist options
  • Save ahvonenj/847668032c77c0efa87c to your computer and use it in GitHub Desktop.
Save ahvonenj/847668032c77c0efa87c to your computer and use it in GitHub Desktop.
Perfect JavaScript update loop with requestAnimationFrame
function timestamp()
{
return window.performance && window.performance.now ? window.performance.now() : new Date().getTime();
}
this.t =
{
now: null,
acc: 0,
dt: 0.01,
last: 0,
step: 1/60,
time: 0,
ft: 0
};
Net.prototype.animate = function(net)
{
net.t.now = timestamp();
net.t.ft = net.t.now - net.t.last;
if(net.t.ft > 0.25)
net.t.ft = 0.25;
net.t.last = net.t.now;
net.t.acc += net.t.ft;
while(net.t.acc >= net.t.dt)
{
net.update(net.t.dt);
net.t.time += net.t.dt;
net.t.acc -= net.t.dt;
}
net.render();
requestAnimationFrame(function(t) { net.animate(net); });
}
Loop()
{
var self = this;
this.t.now = this.timestamp();
this.t.ft = this.t.now - this.t.last;
if(this.t.ft > 0.25)
this.t.ft = 0.25;
this.t.last = this.t.now;
this.t.acc += this.t.ft;
while(this.t.acc >= this.t.dt)
{
this.Update(this.t.dt);
this.t.time += this.t.dt;
this.t.acc -= this.t.dt;
}
this.Draw();
requestAnimationFrame(function(t) { this.Loop(this); }.bind(this));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment