2

Possible Duplicate:
How can I pass a parameter to a setTimeout() callback?
Is there ever a good reason to pass a string to setTimeout?

I want to call a function loadPHPQuote(code) after 1 second. And want to pass the parameter called code which is containing both numbers and text characters. But setTimeout() wasn't work if the code contain a character it is OK with only numbers.

Here is my code

setTimeout('loadPHPQuote('+code+')',1000);

Is there anyone who can help me with this please.....?

Community
  • 1
  • 1

3 Answers3

4

Do this:

setTimeout(function() { loadPHPQuote(code); }, 1000);
  • When you use quotes, it calls eval behind the scene,
  • when you need to pass arguments wrap it in a function like above.
  • To prevent calling function immediately, don't use () in setTimeout or setInterval directly
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

It is not recommended to pass strings as parameters to setTimeout() (see, e.g., MDN). Use an anonymous function instead:

setTimeout( function(){ loadPHPQuote( code ); }, 1000 );
Sirko
  • 72,589
  • 19
  • 149
  • 183
1

You need you parameter to be in quotes, as it is a string you are passing, e.g.:

setTimeout('loadPHPQuote("'+code+'")',1000);
Paddy
  • 33,309
  • 15
  • 79
  • 114