Javascript Object setTimeout

So I’ve been developing a chat room entirely in Javascript and PHP using a lot of ajax. Aside from an eCard I made for friends and family last christmas, I’ve not written more than a few lines of javascript before. I find starting a large project is a good way to learn a language, so off I went…

I wanted to do this properly, so I read up on Javascript OOP development and improved my general knowledge of the excellent jQuery library. I developed the client side script over a week or so and while doing so, found a number of issues with how setTimeout and setInterval work with objects.

Example:

function someObject() {
    this.myVar = 'Test';
    setTimeout(this.myTimeoutCall, 1000);
}
someObject.prototype.myTimeoutCall = function() {
    alert(this.myVar);
}

This alerts out ‘Test’ right? Wrong. It alerts Undefined… Why? Apparently setTimeout and setInterval lose the object scope when they call the timer function. I spent hours in Aptana last night butchering around some Javascript until I came up with 2 functions that ensure your timer code is called in the correct scope, and since there’s little appropriate documentation for it out there, I thought I’d share:

function SetTimeoutObj(o, t, f, a) {

	return setTimeout(function() {

		f.apply(o,a);

	}, t);

}

function SetIntervalObj(o, t, f, a) {

	return setInterval(function() {

		f.apply(o,a);

	}, t);

}

Change your code to use setTimeout(this, time, this.function, [param1, param2, etc]) and hopefully your problems are solved (note: the function parameter list is similar to the original setTimeout, but I moved the duration parameter left one for clarity.)

This entry was posted on Sunday, July 19th, 2009 at 09:19 and is filed under Javascript. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.