我有一些JavaScript代码,看起来像:

function statechangedPostQuestion()
{
  //alert("statechangedPostQuestion");
  if (xmlhttp.readyState==4)
  {
    var topicId = xmlhttp.responseText;
    setTimeout("postinsql(topicId)",4000);
  }
}

function postinsql(topicId)
{
  //alert(topicId);
}

我得到一个错误,topicId没有定义 在我使用setTimeout()函数之前,一切都在工作。

我希望我的postinsql(topicId)函数在一段时间后被调用。 我该怎么办?


当前回答

一般来说,如果需要将函数作为带有特定参数的回调函数传递,则可以使用高阶函数。这在ES6中是非常优雅的:

const someFunction = (params) => () => {
  //do whatever
};

setTimeout(someFunction(params), 1000);

或者如果someFunction是一阶的:

setTimeout(() => someFunction(params), 1000); 

其他回答

在现代浏览器(ie IE11及以上)中,“setTimeout”接收第三个参数,该参数在计时器结束时作为参数发送给内部函数。

例子:

var hello = " hello World"; setTimeout(alert, 1000, hello);

更多的细节:

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout http://arguments.callee.info/2008/11/10/passing-arguments-to-settimeout-and-setinterval/

这是一个已经有“正确”答案的老问题,但我想我要提到另一种没有人在这里提到过的方法。这是从优秀的下划线库复制和粘贴:

_.delay = function(func, wait) {
  var args = slice.call(arguments, 2);
  return setTimeout(function(){ return func.apply(null, args); }, wait);
};

你可以传递尽可能多的参数给setTimeout调用的函数,作为一个额外的奖励(好吧,通常是一个奖励),传递给你的函数的参数的值在你调用setTimeout时被冻结,所以如果它们在setTimeout()被调用和超时之间的某个点上改变了值,嗯…这已经不再令人沮丧了:)

这里有一把小提琴,你可以明白我的意思。

如果你想传递变量作为参数,让我们试试这个

如果要求是函数和var作为帕尔马,那么试试这个

setTimeout((param1,param2) => { 
     alert(param1 + param2);
     postinsql(topicId);
},2000,'msg1', 'msg2')

如果要求只是变量作为参数,那么试试这个 setTimeout((param1,param2) =>{警报(param1 + param2)},2000,' ms1 ', ' ms2 ')

你可以在ES5和ES6上尝试

我是如何解决这个问题的?

就像这样:

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

setTimeout等待一个函数的引用,所以我在一个闭包中创建了它,它解释了我的数据,并返回一个具有我的数据的良好实例的函数!

也许你可以改进这部分:

_deepFunction(_deepData);

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

我在chrome, firefox和IE上测试了它,它执行得很好,我不知道性能如何,但我需要它工作。

一个示例测试:

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

也许你可以改变签名,使其更符合要求:

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)
}

最后来回答最初的问题:

 myNass_setTimeOut( postinsql, 4000, topicId );

希望对大家有所帮助!

Ps:对不起,英语不是我的母语!

你可以尝试'apply()'这样的默认功能,你可以在数组中传递更多的参数作为你的需求

function postinsql(topicId)
{
  //alert(topicId);
}
setTimeout(
       postinsql.apply(window,["mytopic"])
,500);