JavaScript

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

By Niall Kader1 min read

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

};