Javascript: Passing variables with setTimeout and getting it to work
The Problem
If you write any sort of Javascript code then you probably have come across this at some point. Passing a variableto 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. (thanksmakemineatriple)
No comments:
Post a Comment