Calling a function internally using setTimeout

$(document).ready ( function ready() { var tester = $.ajax({ async: false, url: "test_parse.php" }).responseText; document.getElementById('test').innerHTML = tester; setTimeout(ready(), 3000); } ); 

Hi guys, I want to call a function internally like this, but every time I do this, my browser just keeps loading and eventually Apache shuts down (obviously not my expected result). Think you guys could help me figure out a solution? Thanks!

+4
source share
4 answers

setTimeout accepts a function reference:

 setTimeout(ready, 3000); 

not

 setTimeout(ready(), 3000); 

And having said that, I will also do the following:

 $(document).ready ( function ready() { var tester = $.ajax({ url: "test_parse.php", success: function (data) { document.getElementById('test').innerHTML = data; setTimeout(ready, 3000); } }) } ); 

Since async: false block the browser until the data returns from the server

+10
source

It is not right:

 setTimeout(ready(), 3000); 

It is right:

 setTimeout(ready, 3000); 

ready() actually calls the function. ready is just a reference to the function you need.

+6
source

setTimeout expects a function reference as the first parameter, you have a function call that passes the result of the ready () call.

This causes an endless loop.

You need to go to "ready", not "ready ()"

 setTimeout(ready, 3000); 

And if you are trying to queue ajax requests that occur in a structured manner, you want to run setTimeout to succeed after the previous ajax call, and not immediately, otherwise you will get returned and updated ajax results. 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 parameter, which blocks the browser.

+2
source

Why are you trying to call a function inside you? Of course, all you have to do is move setTimeout outside of the function and then call ready () every 3000 ms? What do you want your way out?

0
source

All Articles