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

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

    I know its been 10 yrs since this question was asked, but still, if you have scrolled till here, i assume you're still facing some issue. The solution by Meder Omuraliev is the simplest one and may help most of us but for those who don't want to have any binding, here it is:

    1. Use Param for setTimeout
    setTimeout(function(p){
    //p == param1
    },3000,param1);
    
    1. Use Immediately Invoked Function Expression(IIFE)
    let param1 = 'demon';
    setTimeout(function(p){
        // p == 'demon'
    },2000,(function(){
        return param1;
    })()
    );
    
    1. Solution to the question
    function statechangedPostQuestion()
    {
      //alert("statechangedPostQuestion");
      if (xmlhttp.readyState==4)
      {
        setTimeout(postinsql,4000,(function(){
            return xmlhttp.responseText;
        })());
      }
    }
    
    function postinsql(topicId)
    {
      //alert(topicId);
    }
    

提交回复
热议问题