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

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

    My answer:

    setTimeout((function(topicId) {
      return function() {
        postinsql(topicId);
      };
    })(topicId), 4000);
    

    Explanation:

    The anonymous function created returns another anonymous function. This function has access to the originally passed topicId, so it will not make an error. The first anonymous function is immediately called, passing in topicId, so the registered function with a delay has access to topicId at the time of calling, through closures.

    OR

    This basically converts to:

    setTimeout(function() {
      postinsql(topicId); // topicId inside higher scope (passed to returning function)
    }, 4000);
    

    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.

提交回复
热议问题