public
Created — forked from PaulKinlan/gist:4160675

Encapsulating Request Animation Frame

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/*
Javascript is a funny thing.
Here are two things that will hit you with requestAnimationFrame
 
1) If you alias the window.requestAnimationFrame function on to anything other
than a window object, you get an Illegal Invocation Error.
 
You can solve this by using call() with the window object set.
 
2) Your callback will be called with the this method set to the window object.
You can solve this by calling bind() on your callback function with your game class.
 
*/
 
var Game = function(win) {
this.requestAnimationFrame = (function(w) {
return w.requestAnimationFrame ||
w.webkitRequestAnimationFrame ||
w.mozRequestAnimationFrame ||
w.oRequestAnimationFrame ||
w.msRequestAnimationFrame ||
function(callback) {
w.setTimeout(callback, 1000 / 60);
};
})(win).bind(win);
 
this.update_ = this.update.bind(this);
this.requestAnimationFrame(this.update_);
};
 
Game.prototype.update = function() {
// Do the game logic.
console.log("Update");
this.requestAnimationFrame(this.update_);
};
 
var g = new Game(window);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.