Siu Lun

Passing variables to setTimeout in javascript

by Siu Lun on May.29, 2009, under Programming, Web

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 are closed.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...