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?
The answer by David Meister seems to take care of parameters that may change immediately after the call to setTimeout() but before the anonymous function is called. But it's too cumbersome and not very obvious. I discovered an elegant way of doing pretty much the same thing using IIFE (immediately inviked function expression).
In the example below, the
currentList
variable is passed to the IIFE, which saves it in its closure, until the delayed function is invoked. Even if the variablecurrentList
changes immediately after the code shown, thesetInterval()
will do the right thing.Without this IIFE technique, the
setTimeout()
function will definitely get called for eachh2
element in the DOM, but all those calls will see only the text value of the lasth2
element.The easiest cross browser solution for supporting parameters in setTimeout:
If you don't mind not supporting IE 9 and lower:
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
How i resolved this stage ?
just like that :
setTimeout wait a reference to a function, so i created it in a closure, which interprete my data and return a function with a good instance of my data !
Maybe you can improve this part :
I tested it on chrome, firefox and IE and it execute well, i don't know about performance but i needed it to be working.
a sample test :
Maybe you can change the signature to make it more complient :
And finaly to answer the original question :
Hope it can help !
ps : sorry but english it's not my mother tongue !