Skip to content

Instantly share code, notes, and snippets.

@digitalicarus
Created September 28, 2014 17:04
Show Gist options
  • Select an option

  • Save digitalicarus/f34dcba5de2da28141b1 to your computer and use it in GitHub Desktop.

Select an option

Save digitalicarus/f34dcba5de2da28141b1 to your computer and use it in GitHub Desktop.
Another Game Loop
function ChronoTron(conf) {
function gots (name, type) {
return (
(type === 'Array') ?
conf[name] instanceof Array :
conf[name] && typeof conf[name] === type
);
}
switch (true) {
case typeof conf !== 'object':
throw "gimme object";
case !gots('update', 'function'):
throw "need function member called 'update'";
case !gots('draw', 'function'):
throw "need function member called 'draw'";
case !gots('fps', 'number'):
throw "need number member called 'fps'";
}
for(i in conf) { this[i] = conf[i]; }
this.mspf = (1000 / this.fps)|0; // slightly more aggressive
this.stuff = {}; // don't garbage collect me bro
}
ChronoTron.prototype.reqAnimFrame = (function () {
return (
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function (cb) { setTimeout(cb, 0); }
).bind(window);
})();
ChronoTron.prototype.__update = function (n) {
for (; n--; n > 0) { this.update(); }
};
ChronoTron.prototype.__cycle = function () {
this.__update((((new Date().getTime()) - this.stuff.last)/this.mspf)|0);
this.reqAnimFrame(this.draw);
this.stuff.last = new Date().getTime();
!this.pause && setTimeout(this.__cycle.bind(this), this.mspf);
};
ChronoTron.prototype.start = function () {
this.pause = false;
this.stuff.last = new Date().getTime();
this.__cycle();
};
ChronoTron.prototype.stop = function () {
this.pause = true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment