javascript - How can I pass a parameter to a setTimeout() callback? -


i have javascript code looks like:

function statechangedpostquestion() {   //alert("statechangedpostquestion");   if (xmlhttp.readystate==4)   {     var topicid = xmlhttp.responsetext;     settimeout("postinsql(topicid)",4000);   } }  function postinsql(topicid) {   //alert(topicid); } 

i error topicid not defined working before used settimeout() function.

i want postinsql(topicid) function called after time. should do?

settimeout(function() {     postinsql(topicid); }, 4000) 

you need feed anonymous function parameter instead of string, latter method shouldn't work per ecmascript specification browsers lenient. proper solution, don't ever rely on passing string 'function' when using settimeout() or setinterval(), it's slower because has evaluated , isn't right.

update:

as hobblin said in comments question, can pass arguments function inside settimeout using function.prototype.bind()

example:

settimeout(postinsql.bind(null, topicid), 4000); 

Comments