Passing parameters to a function called with setTimeout

When creating my news ticker plugin, I came across a slight complication when using setTimeout() to calling a function which needed parameters passed to it.

Not having had much call to use setTimeout in the past, I simply put:

setTimeout(myFunction(parameter),myTimeout);

but that doesn’t work. An apparent solution (until tried in Internet Explorer) is:

setTimeout(myFunction,myTimeout,parameter);

It wasn’t as easy as I expected to find out how to get around this, but it turns out that all is needed is a “closure”:

setTimeout(function(){myFunction(parameter)},myTimeout);

5 Comments »

  1. Closures are arguably the great secret of Javascript: the way variable scope stacks get frozen at the point of closure (and hence variables persist within the closure) is quite subtle and catches most out, including me!

    Be warned that IEx has a garbage-collector subtlety, though; I think that if you reference a DOM variable in a Javascript closure, then the collection mechanism gets confused and it doesn’t get trashed at the end of the request: eventually this becomes a memory leak. I think it’s because DOM variables and internal JS variables get collected by two different collectors, and they don’t communicate properly about what’s no longer being used.

    I think you can fix this by setting the variable to null:

    setTimeout(function(){myFunction(parameter); parameter = null},myTimeout);

    This explicitly sets the garbage collection in motion.

    Comment by J-P Stacey — October 29, 2007 @ 9:15 am

  2. Thanks for that, J-P - I agree they seem to be rather a secret! I’ve added this into the news ticker and put up the new release

    Comment by bryan — October 31, 2007 @ 4:37 am

  3. I was pulling my hair out. The books seem to gloss over this like I should have known it and then go on to tell me some obscure thing I’ll never use. I cannot thank you enough!

    Comment by Greg — November 7, 2007 @ 1:47 am

  4. This is great. I was getting rather frustrated with IE not accepting the 3rd parameter and could not find a way around it for my code. Now I dont have to.

    Comment by Matt — August 7, 2008 @ 8:25 am

  5. Great tip!! I’ve been looking for this solution for a while now. Thanks!

    Comment by Jake — August 13, 2008 @ 3:47 am

RSS feed for comments on this post. TrackBack URI

Leave a comment