Wednesday, May 11, 2011

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);

Reference:                                                                                                      
  1. http://www.makemineatriple.com/2007/10/passing-parameters-to-a-function-called-with-settimeout

No comments:

Post a Comment