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?
The JS setTimeout() method will call a function after the time specified in milliseconds (1000 ms = 1 second) has passed. The specified function will be executed once. If you need to run a function multiple times, use the setInterval() method.
Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute. All other statements that are not part of setTimeout() are blocking which means no other statement will execute before the current statement finishes.
There are two most common built-in timer functions, setTimeout and setInterval , which can be used to call a function at a later time. For an example usage: setTimeout(function () { console.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With