Can't stop making
Home
29th May, 2009
Friday

Passing variables to setTimeout in javascript

I've been working on a javascript menu effect today. I don't use javascript enough to remember all the syntax, let alone browser support.

So anyway, I had to use setTimeout in order to delay effect changes for human interactions, but I had to pass a couple of variables. Now following some javascript tutorial sites my original code was like this:

setTimeout(function(a,b) { alert(a+'-'+b); }, 100, 'a input', 'b input');

This worked on Firefox 3 which is my standard dev platform.

When I decide to test on IE though, all I get is 'undefined' coming up.

A quick search on the net revealed that I need to actually do:

var a = 'a input';
var b ='b input';

setTimeout(function(){ alert_func(a,b) },100);

function alert_func(a,b){
   alert(a+'-'+b);
}

to make it work on IE.

Note: Apparently we also need to do a = null; and b=null; after the alert_func(a,b) call in the inline function in order to avoid a IE memory leak. (Have not tested or confirmed myself)

Tested on: IE8 and IE8 with compatbility mode
Credit goes to: MakeMineATriple's blog and most of all the comments below it.

Comments

Leave a comment

Any published comments will adhere to the etiquette policy and all e-mail addresses will be treated in accordance to the privacy policy.

  • If you see this, something's wrong with Twitter.

Blatant Plug

Need a new CPU or graphics card? Get AMD.

AMD Vision and AMD Radeon Graphics

Support

I've pledged my support to these organisations, and I think you should too.

  • Google+
  • Follow ronaldslc on Twitter
  • View Ronald Chan's profile on LinkedIn