views:

45

answers:

3

I want to call function with arguement periodically.

I tried setTimeout("fnName()",timeinseconds); and it is working.

But when I add an arguement it won't work. eg: setTimeout("fnName('arg')",timeinseconds);

+7  A: 

You can add an anonymous function:

setTimeout(function() { fnName("Arg"); }, 1000);
Pekka
worth mentioning - this is called "currying" :)
Yonatan Karni
@Yonatan nice, never heard of that :) Do you mean the putting the call into an anonymous function?
Pekka
setTimeout is not calling function repeatedly, but setInterval calling repeatedly
shinod
@shinod you're right; the principle is the same.
Pekka
@pekka - yes, it's a mathematical notion. from wikipedia: "currying is the technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of functions each with a single argument."although I wonder if it's still currying when you're not passing ANY arguments :)
Yonatan Karni
+2  A: 

Use an anonymous function, like this:

setTimeout(function() { fnName('arg'); }, time);

In general, never pass a string to setTimeout() or setInterval() if you can avoid it, there are other side-effects besides being bad practice...e.g. the scope you're in when it runs.

Just as a side-note, if you didn't need an argument, it's just:

setTimeout(fnName, time);
Nick Craver
A: 

setTimeout accepts an expression or a function name or an anonymous function but NO () operator.

() will start executing the function immediately and results in setTimeout accept an invalid parameter.

unigg