Calling a function inside itself using setTimeout
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 fig开发者_开发知识库ure out a solution?
setTimeout takes a function reference:
setTimeout(ready, 3000);
not
setTimeout(ready(), 3000);
And that being said, I would also do this:
$(document).ready (
function ready() {
var tester = $.ajax({
url: "test_parse.php",
success: function (data) {
document.getElementById('test').innerHTML = data;
setTimeout(ready, 3000);
}
})
}
);
Because async: false
will lock up the browser until that data returns from the server
This is wrong:
setTimeout(ready(), 3000);
This is right:
setTimeout(ready, 3000);
ready()
is actually invoking the function. ready
is simply a reference to the function, which is what you want.
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()"
setTimeout(ready, 3000);
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.
$.ajax({
// your ajax settings
}).success(function () {
// fire off the next one 3 secs after the last one completes
setTimeout(ready, 3000);
});
This is better than using the async: false setting, which blocks the browser.
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?
精彩评论