Friday, January 25, 2008

setTimeout / setInterval and object scope

I have found over time, the need for setTimeout/setInterval is pretty rare... however, when the need does arrive, it is an invaluable tool!

The problem that I have consistently run into as of late (now that I am writing primarily object based JavaScript) is that when you use these functions, you loose the scope of your object. (i.e. if you call setTimeout(this.myFunc,900); this no longer refers to your object, but rather window, causing your script to fail). In search of a solution, I found an interesting article by Kelvo.

Klevo points out that in FireFox, setTimeout allows you to pass an additional parameter stating the implied scope. So by simply changing our command to: setTimeout(function(that) { that.methodToCall(); }, time, this); fixes the issues with scope... We basic create a proxy function that accepts an object as it's only paramater and gives us access to of that functions methods! This is a beautiful solution, if all you are developing for is FireFox.

From there, I found Alex's article who gives a simple yet elegant workaround for IE as well.

Check it out, it's absolutely worth a read for anyone who has run into trouble with setTimeout and JavaScript objects.

1 comment:

Marc said...

I had the same problem with setTimeout and setInterval, and wrote a simple workaround that I've tested in IE8, Firefox 3, Chrome 2, Safari 4 and Opera 9.