使用 setTimeout 调用自身内部的函数
我想像这样调用自身内部的函数:
$(document).ready (
function ready() {
var tester = $.ajax({
async: false,
url: "test_parse.php"
}).responseText;
document.getElementById('test').innerHTML = tester;
setTimeout(ready(), 3000);
}
);
但是每次我这样做时,我的浏览器都会继续加载,最终 Apache 关闭(显然不是我预期的结果)。你能帮我想出一个解决办法吗?
I want to call a function within itself like this:
$(document).ready (
function ready() {
var tester = $.ajax({
async: false,
url: "test_parse.php"
}).responseText;
document.getElementById('test').innerHTML = tester;
setTimeout(ready(), 3000);
}
);
But every time I do this my browser just keeps loading and eventually Apache shuts down (obviously not my expected result). Could you help me to figure out a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
setTimeout 接受一个函数引用:
not
话虽这么说,我也会这样做:
因为
async: false
会锁定浏览器,直到数据从服务器返回setTimeout takes a function reference:
not
And that being said, I would also do this:
Because
async: false
will lock up the browser until that data returns from the server这是错误的:
这是正确的:
ready()
实际上是在调用该函数。ready
只是对函数的引用,这就是您想要的。This is wrong:
This is right:
ready()
is actually invoking the function.ready
is simply a reference to the function, which is what you want.setTimeout 需要一个函数引用作为第一个参数,您有一个函数调用,它传递调用 read() 的结果。
这导致了无限循环。
您需要传入“ready”,而不是“ready()”
,如果您尝试对以结构化顺序发生的 ajax 请求进行排队,则需要在上一次 ajax 调用成功后触发 setTimeout,而不是立即触发,否则您将看到 ajax 结果以任意时间间隔返回和更新,具体取决于服务器如何响应每个请求。
这比使用 async: false 设置要好,后者会阻止浏览器。
setTimeout expects a function reference as the first parameter, you have a function invocation which is passing the result of calling ready().
This is causing an infinite loop.
You need to pass in "ready", not "ready()"
And if you're trying to queue ajax requests that happen in a structured order, you'll want to fire the setTimeout on success after the previous ajax call, not immediately, otherwise you'll have ajax results returning and updating at arbitrary intervals depending on how the server responds to each request.
This is better than using the async: false setting, which blocks the browser.
你为什么要尝试在其内部调用该函数?当然,您需要做的只是将 setTimeout 移到函数之外,然后每 3000 毫秒调用 read() 一次?你希望你的输出是什么?
Why are you trying to call the function within itself? Surely all you need to do is move setTimeout outside of the function, then call ready() every 3000ms? What'l do you want your output to be?