我如何传递参数到setTimeout()回调? [英] How can I pass a parameter to a setTimeout() callback?

查看:150
本文介绍了我如何传递参数到setTimeout()回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

函数postinsql(topicId)
{
// alert(topicId);
}

我收到一个错误, topicId 未定义
在使用 setTimeout()函数之前一切正常。



我想要一段时间后调用 postinsql(topicId)函数。
我应该怎么办?

解决方案

  setTimeout(function b $ b postinsql(topicId); 
},4000)

匿名函数作为参数而不是字符串,后一种方法甚至不能根据ECMAScript规范工作,但浏览器只是宽松。这是正确的解决方案,不要依赖于使用 setTimeout() setInterval()传递字符串作为' code>,因为它必须被计算,并且它是不正确的。



更新:

正如Hobblin在对这个问题的评论中说,现在你可以使用 Function.prototype.bind()



示例:

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


I have some JavaScript code that looks like:

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

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

I get a error that topicId is not defined Everything was working before i used the setTimeout() function.

I want my postinsql(topicId) function to be called after some time. What should i do?

解决方案

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

You need to feed an anonymous function as a parameter instead of a string, the latter method shouldn't even work per the ECMAScript specification but browsers are just lenient. This is the proper solution, don't ever rely on passing a string as a 'function' when using setTimeout() or setInterval(), it's slower because it has to be evaluated and it just isn't right.

UPDATE:

As Hobblin said in his comments to the question, now you can pass arguments to the function inside setTimeout using Function.prototype.bind()

Example:

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

这篇关于我如何传递参数到setTimeout()回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆