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


当前回答

@Jiri Vetyska感谢你的帖子,但你的例子有问题。 我需要传递的目标是悬停(这)到一个超时函数,我尝试了你的方法。在IE9测试-不工作。 我也做了一些研究,这里指出的第三个参数是使用的脚本语言。没有提到额外的参数。

所以,我遵循@meder的答案,用这段代码解决了我的问题:

$('.targetItemClass').hover(ItemHoverIn, ItemHoverOut);

function ItemHoverIn() {
 //some code here
}

function ItemHoverOut() {
    var THIS = this;
    setTimeout(
        function () { ItemHoverOut_timeout(THIS); },
        100
    );
}
function ItemHoverOut_timeout(target) {
    //do something with target which is hovered out
}

霍普,这对别人有用。

其他回答

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

请注意,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("postinsql(" + 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);