Variables, setTimeout and Internet Explorer

If you write any sort of Javascript code then you probably have come across this at some point. Passing a variable to a function triggered from setTimeout doesn’t work in IE. Luckily I stumbled across a widely unknown solution!

The Problem with setTimeout

If you write any sort of Javascript code then you probably have come across this at some point. Passing a variable to a function triggered from setTimeout doesn’t work in IE. Luckily I stumbled across a widely unknown solution!

Normally you would use this:

setTimeout(“myFunction(‘“+variable+”’)”,1000);

but you are meant to be able to use this:

setTimeout(myFunction,1000,variable);

but frustratingly it doesn’t work in any version of Internet Explorer.

The Solution

Well, it is surprisingly simple. You just need to encase your function name in a ‘closure’. i.e. a function declaration. This is surprisingly similar to flash actionscript which is of course javascript based. Why didn’t I think of this before??

So you simply put:

setTimeout(function(){myFunction(variable); variable = null},1000);

the ‘variable = null’ is to stop a memory leak as the variable is not deleted as it should be.

(thanks makemineatriple)