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


当前回答

你必须像这样从setTimeOut函数调用中删除引号:

setTimeout(postinsql(topicId),4000);

其他回答

我知道这个问题已经问了10年了,但是,如果你一直滚动到这里,我认为你仍然面临着一些问题。Meder Omuraliev的解决方案是最简单的,可能对我们大多数人都有帮助,但对于那些不想有任何约束的人来说,下面是:

setTimeout使用Param

setTimeout(function(p){
//p == param1
},3000,param1);

使用立即调用的函数表达式

let param1 = 'demon';
setTimeout(function(p){
    // p == 'demon'
},2000,(function(){
    return param1;
})()
);

问题的解决方法

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

function postinsql(topicId)
{
  //alert(topicId);
}
setTimeout(function() {
    postinsql(topicId);
}, 4000)

您需要将匿名函数作为参数而不是字符串提供,根据ECMAScript规范,后一种方法甚至不应该工作,但浏览器只是宽容。这是正确的解决方案,当使用setTimeout()或setInterval()时,不要依赖于传递字符串作为“函数”,它更慢,因为它必须被计算,这是不正确的。

更新:

正如Hobblin在他对问题的评论中所说,现在你可以使用function .prototype.bind()将参数传递给setTimeout内的函数。

例子:

setTimeout(postinsql.bind(null, topicId), 4000);

//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);

我知道它很老了,但我想加入我喜欢的味道。

我认为实现这一点的一种相当易读的方法是将topicId传递给一个函数,该函数反过来使用参数在内部引用主题ID。即使外部的topicId不久后将被更改,该值也不会改变。

var topicId = xmlhttp.responseText;
var fDelayed = function(tid) {
  return function() {
    postinsql(tid);
  };
}
setTimeout(fDelayed(topicId),4000);

或短:

var topicId = xmlhttp.responseText;
setTimeout(function(tid) {
  return function() { postinsql(tid); };
}(topicId), 4000);

支持setTimeout参数的最简单的跨浏览器解决方案:

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

如果你不介意不支持ie9及以下版本:

setTimeout(postinsql, 4000, topicId);

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout