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

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

问题描述

我有一些如下所示的 JavaScript 代码:

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

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

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

我希望在一段时间后调用我的 postinsql(topicId) 函数.我该怎么办?

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

推荐答案

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

您需要提供一个匿名函数作为参数而不是字符串,后一种方法甚至不应该按照 ECMAScript 规范工作,但浏览器只是宽松的.这是正确的解决方案,在使用 setTimeout()setInterval() 时,永远不要依赖将字符串作为函数"传递,它会更慢,因为它必须被评估,它就是不对的.

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.

正如 Hobblin 在他的评论中所说 的问题,现在您可以使用 Function.prototype.bind().

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

示例:

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

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

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