我有一些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)函数在一段时间后被调用。 我该怎么办?


当前回答

//Some function, with some arguments, that need to run with arguments var a = function a(b, c, d, e){console.log(b, c, d, e);} //Another function, where setTimeout using for function "a", this have the same arguments var f = function f(b, c, d, e){ setTimeout(a.apply(this, arguments), 100);} f(1,2,3,4); //run //Another function, where setTimeout using for function "a", but some another arguments using, in different order var g = function g(b, c, d, e){ setTimeout(function(d, c, b){a.apply(this, arguments);}, 100, d, c, b);} g(1,2,3,4);

其他回答

在现代浏览器(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/

这适用于所有浏览器(IE是一个奇怪的)

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

用一个简单的带有两个参数的加法函数来回答这个问题。

var x = 3, y = 4;

setTimeout(function(arg1, arg2) { 
  return () => delayedSum(arg1, arg2);
}(x, y), 1000); 

function delayedSum(param1, param2) {
     alert(param1 + param2); // 7
}

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

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

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

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

你可以在ES5和ES6上尝试

我的回答:

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

解释:

创建的匿名函数返回另一个匿名函数。该函数可以访问最初传递的topicId,因此不会出错。第一个匿名函数被立即调用,并传入topicId,因此具有延迟的注册函数在调用时可以通过闭包访问topicId。

OR

这基本上可以转换为:

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

编辑:我看到了同样的答案,所以看看他的。但我没有偷他的答案!我只是忘了看。阅读解释,看看它是否有助于理解代码。