Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 figure out a solution?

like image 406
Vivek Avatar asked Sep 10 '11 04:09

Vivek


People also ask

How do you call a function in setTimeout?

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.

Is setTimeout a blocking call?

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.

Is setTimeout an inbuilt function?

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.


2 Answers

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

like image 180
Joe Avatar answered Oct 09 '22 11:10

Joe


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.

like image 7
Travis Webb Avatar answered Oct 09 '22 10:10

Travis Webb