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

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

    How i resolved this stage ?

    just like that :

    setTimeout((function(_deepFunction ,_deepData){
        var _deepResultFunction = function _deepResultFunction(){
              _deepFunction(_deepData);
        };
        return _deepResultFunction;
    })(fromOuterFunction, fromOuterData ) , 1000  );
    

    setTimeout wait a reference to a function, so i created it in a closure, which interprete my data and return a function with a good instance of my data !

    Maybe you can improve this part :

    _deepFunction(_deepData);
    
    // change to something like :
    _deepFunction.apply(contextFromParams , args); 
    

    I tested it on chrome, firefox and IE and it execute well, i don't know about performance but i needed it to be working.

    a sample test :

    myDelay_function = function(fn , params , ctxt , _time){
    setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
                var _deepResultFunction = function _deepResultFunction(){
                    //_deepFunction(_deepData);
                    _deepFunction.call(  _deepCtxt , _deepData);
                };
            return _deepResultFunction;
        })(fn , params , ctxt)
    , _time) 
    };
    
    // the function to be used :
    myFunc = function(param){ console.log(param + this.name) }
    // note that we call this.name
    
    // a context object :
    myObjet = {
        id : "myId" , 
        name : "myName"
    }
    
    // setting a parmeter
    myParamter = "I am the outer parameter : ";
    
    //and now let's make the call :
    myDelay_function(myFunc , myParamter  , myObjet , 1000)
    
    // this will produce this result on the console line :
    // I am the outer parameter : myName
    

    Maybe you can change the signature to make it more complient :

    myNass_setTimeOut = function (fn , _time , params , ctxt ){
    return setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
                var _deepResultFunction = function _deepResultFunction(){
                    //_deepFunction(_deepData);
                    _deepFunction.apply(  _deepCtxt , _deepData);
                };
            return _deepResultFunction;
        })(fn , params , ctxt)
    , _time) 
    };
    
    // and try again :
    for(var i=0; i<10; i++){
       myNass_setTimeOut(console.log ,1000 , [i] , console)
    }
    

    And finaly to answer the original question :

     myNass_setTimeOut( postinsql, 4000, topicId );
    

    Hope it can help !

    ps : sorry but english it's not my mother tongue !

提交回复
热议问题