Search code examples
javascriptjqueryrecursionstackstack-overflow

Will this javascript code create a big stack?


function startAJAXcalls()
{
   setTimeout(function(){
      getXMLData();
      startAJAXcalls();
       },
       10000
   );
}

startAJAXcalls();

I lifted this code from the Head First JQuery book. It says that this will guarantee that there is not a buildup of requests, which I agree is true but I am worried about a huge chain of function calls that are not allowed to exit. Is every call to startAJAXcalls() in its own stack because of the asynchronous calls to startAJAXcalls() via setTimeout()?


Solution

  • No, because once you call setTimeout the function will exit and then the next call to startAJAXcalls will start with a new stack frame because the setTimeout just queues the callback function to a list of things that the Javascript engine keeps until they should be executed. Think of there being one static list of functions and each time you call setTimeout it adds your function to that list. At some point later on the Javascript engine executes that callback, which just puts another callback into the same list and the Javacript engine keeps looping emptying and calling callbacks from the list when the time comes.

    Really good information on how Javascript implements timers here: http://ejohn.org/blog/how-javascript-timers-work/