I have some JavaScript code that looks like:
function statechangedPostQuestion()
{
//alert("statechangedPostQuestion");
if (xmlhttp.readyState==4)
{
var topicId = xmlhttp.responseText;
setTimeout("postinsql(topicId)",4000);
}
}
function postinsql(topicId)
{
//alert(topicId);
}
I get a error that topicId
is not defined
Everything was working before i used the setTimeout()
function.
I want my postinsql(topicId)
function to be called after some time.
What should i do?
Replace
with
or better still, replace the string expression with an anonymous function
EDIT:
Brownstone's comment is incorrect, this will work as intended, as demonstrated by running this in the Firebug console
Note that I'm in agreeance with others that you should avoid passing a string to
setTimeout
as this will calleval()
on the string and instead pass a function.After doing some research and testing, the only correct implementation is:
setTimeout will pass all extra parameters to your function so they can be processed there.
The anonymous function can work for very basic stuff, but within instance of a object where you have to use "this", there is no way to make it work. Any anonymous function will change "this" to point to window, so you will lose your object reference.
if you want to pass variable as param lets try this
if requirement is function and var as parmas then try this
if requirement is only variables as a params then try this
You can try this with ES5 and ES6
this works in all browsers (IE is an oddball)
You can try default functionality of 'apply()' something like this, you can pass more number of arguments as your requirement in the array
I know it's old but I wanted to add my (preferred) flavour to this.
I think a pretty readable way to achieve this is to pass the
topicId
to a function, which in turn uses the argument to reference the topic ID internally. This value won't change even iftopicId
in the outside will be changed shortly after.or short: