shin
shin

Reputation: 1681

to call a javascript function periodically

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

Upvotes: 5

Views: 3735

Answers (3)

unigg
unigg

Reputation: 464

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.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630409

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

Upvotes: 2

Pekka
Pekka

Reputation: 449435

You can add an anonymous function:

setTimeout(function() { fnName("Arg"); }, 1000);

Upvotes: 12

Related Questions