Passing parameters to a function called with setTimeout


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

Post by

Bryan Gullan

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

© Bryan Gullan