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?
My answer:
Explanation:
OR
This basically converts to:
EDIT: I saw the same answer, so look at his. But I didn't steal his answer! I just forgot to look. Read the explanation and see if it helps to understand the code.
Note that the reason topicId was "not defined" per the error message is that it existed as a local variable when the setTimeout was executed, but not when the delayed call to postinsql happened. Variable lifetime is especially important to pay attention to, especially when trying something like passing "this" as an object reference.
I heard that you can pass topicId as a third parameter to the setTimeout function. Not much detail is given but I got enough information to get it to work, and it's successful in Safari. I don't know what they mean about the "millisecond error" though. Check it out here:
http://www.howtocreate.co.uk/tutorials/javascript/timers
I think you want:
You need to feed an anonymous function as a parameter instead of a string, the latter method shouldn't even work per the ECMAScript specification but browsers are just lenient. This is the proper solution, don't ever rely on passing a string as a 'function' when using
setTimeout()
orsetInterval()
, it's slower because it has to be evaluated and it just isn't right.UPDATE:
As Hobblin said in his comments to the question, now you can pass arguments to the function inside setTimeout using
Function.prototype.bind()
Example:
In general, if you need to pass a function as a callback with specific parameters, you can use higher order functions. This is pretty elegant with ES6:
Or if
someFunction
is first order:In modern browsers, the "setTimeout" receives a third parameter that is sent as parameter to the internal function at the end of the timer.
Example:
More details: