Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Encapsulating Request Animation Frame
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);
this.update_ = this.update.bind(this);
Game.prototype.update = function() {
// Do the game logic.
var g = new Game(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment