JavaScript’s setTimeout and how to use it with your methods

Update: My solution does not work in IE. Look at this article for comprehensive info.

While working on Chatcreator’s Chatbox I run into problems with JavaScript’s setTimeout function. I would like to write down what I learned. It may save you some time, next time you’ll need to use this function.

Shortly about setTimeout

setTimeout is a simple JavaScript function used to repeatedly call some function after a specified amount of time. It takes two required parameters and an unspecified number of optional ones. Like this:

setTimeout(functionToCall, time, param1, param2, ....);functionToCall is the name of the function which will be called after time millisecond. You either use reference like in the example above or a string representing a call to the function:

setTimeout('functionToCall()', time, ...)The optional parameters can be used to pass any number of parameters to our functionToCall.

Where’s the catch?

Everything works as expected until you try to call a method inside your ‘class’ (there are no real classes in JavaScript). Something like this won’t work:

setTimeout(this.methodToCall, time);Passing a string representation instead of reference doesn’t work either.

The solution

I found the solution after a while searching in Google Code Search. The above example needs to be rewritten like this:

setTimeout(function(thisObj) { thisObj.methodToCall(); }, time, this);Here we are passing reference to our class as an optional parameter of the setTimeout function. In the called function we catch it and suddenly we can use it to call our method. I have no idea why such a simple thing needs to be so complicated but it only demonstrates that you need to learn a few tricks when you want to do real OOP in JavaScript.