Skip to main content

Passing parameters to a function in setTimeout()

While working on some 'animation' effect on one of my pages, I came across a problem when using setTimeout(). I am using it to call a function repeatedly in certain interval. I am not much into javascript so had quite a trouble figuring it out. If the function which is being called does not have any input parameters,
setTimeout(MyFunc(),10); // calls 'MyFunc' function every 10 ms.
But my 'Animate' function takes a parameter ( divId ),so I tried
setTimeout(Animate(divId),10); // wrong !!
This did not work.
The correct way to call a function with parameters in setTimeout function is.
setTimeout(function(){Animate(divId);}, 10);
This concept is called 'Closure' in javascript.
Just wanted to share...

Comments

  1. It should work fine with quotes.

    setTimeout("Animate(divId)", 10)

    ReplyDelete

Post a Comment