When using setTimeout(), setInterval(), or requestAnimationFrame()

Remember that the scope of 'this' will be global when the callback function for a setTimeout() is triggered. Same goes for setInterval() and requestAnimationFrame().

This one has gotten me more than once.

// This won't work...
someObject.someMethod = function(){
requestAnimationFrame(function(){
this.someOtherMethod();
});
};

 

This will work:

someObject.someMethod = function(){

var self = this;
requestAnimationFrame(function(){
self.someOtherMethod();
});

};