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

前端 未结 28 1988
既然无缘
既然无缘 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:02

    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 if topicId in the outside will be changed shortly after.

    var topicId = xmlhttp.responseText;
    var fDelayed = function(tid) {
      return function() {
        postinsql(tid);
      };
    }
    setTimeout(fDelayed(topicId),4000);
    

    or short:

    var topicId = xmlhttp.responseText;
    setTimeout(function(tid) {
      return function() { postinsql(tid); };
    }(topicId), 4000);
    

提交回复
热议问题