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

前端 未结 28 1895
既然无缘
既然无缘 2020-11-21 07:31

I have some JavaScript code that looks like:

function statechangedPostQuestion()
{
  //alert("statechangedPostQuestion");
  if (xmlhttp.readyState==         


        
28条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 08:13

    Some answers are correct but convoluted.

    I am answering this again, 4 years later, because I still run into overly complex code to solve exactly this question. There IS an elegant solution.

    First of all, do not pass in a string as the first parameter when calling setTimeout because it effectively invokes a call to the slow "eval" function.

    So how do we pass in a parameter to a timeout function? By using closure:

    settopic=function(topicid){
      setTimeout(function(){
        //thanks to closure, topicid is visible here
        postinsql(topicid);
      },4000);
    }
    
    ...
    if (xhr.readyState==4){
      settopic(xhr.responseText);
    }
    

    Some have suggested using anonymous function when calling the timeout function:

    if (xhr.readyState==4){
      setTimeout(function(){
        settopic(xhr.responseText);
      },4000);
    }
    

    The syntax works out. But by the time settopic is called, i.e. 4 seconds later, the XHR object may not be the same. Therefore it's important to pre-bind the variables.

提交回复
热议问题