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


当前回答

请注意,topicId在错误消息中“未定义”的原因是在执行setTimeout时它作为一个局部变量存在,而在延迟调用postinsql时不存在。变量生存期尤其重要,特别是在尝试将“this”作为对象引用传递时。

我听说您可以将topicId作为第三个参数传递给setTimeout函数。没有给出太多细节,但我得到了足够的信息来让它工作,它在Safari中是成功的。我不知道他们所说的“毫秒误差”是什么意思。看看这里:

http://www.howtocreate.co.uk/tutorials/javascript/timers

其他回答

//这是三个非常简单明了的答案:

function fun() {
    console.log(this.prop1, this.prop2, this.prop3);
}

let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };

let bound = fun.bind(obj);

setTimeout(bound, 3000);

 // or

function funOut(par1, par2, par3) {

  return function() { 

    console.log(par1, par2, par3);

  }
};

setTimeout(funOut('one', 'two', 'three'), 5000);

 // or

let funny = function(a, b, c) { console.log(a, b, c); };

setTimeout(funny, 2000, 'hello', 'worldly', 'people');

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

setTimeout(postinsql(topicId),4000);

setTimeout是WHAT WG定义的DOM的一部分。

https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html

方法为:-

Handle = self。setTimeout(处理程序[,timeout[,参数…]]) 在超时毫秒后安排一个超时运行处理程序。任何 参数直接传递给处理程序。

setTimeout(postinsql, 4000, topicId);

显然,IE10支持额外的参数。或者,您也可以使用setTimeout(postinsql。bind(null, topicId), 4000);,但是传递额外的参数更简单,这是更可取的。

历史事实:在VBScript时代,在JScript中,setTimeout的第三个参数是语言,作为一个字符串,默认为“JScript”,但可以选择使用“VBScript”。https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa741500 (v % 3 dvs.85)

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

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

var x = 3, y = 4;

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

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