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();
});

};

Add a Comment...

 

Comments

Howdy would you mind letting me know which web host you're using? I've loaded your blog in 3 completely different browsers and I must say this blog loads a lot quicker then most. Can you suggest a good internet hosting provider at a honest price? Thanks, I appreciate it! fotbollskläder barn - 5/16/2017

JohnMcAlr Liverpool EstebanPi StaciaLwc Elfenbenskusten RonStubbs EliBaylee Elfenbenskusten ScottClor RitaCorby Osterrike MadelineN TaneshaOi Valencia LVUBruce - 3/08/2017