6

Suppose I want to send an asynchronous AJAX request to the server, and when it responds send another request and repeat forever:

function sendXHR(url, callback) {
    // Send XMLHttpRequest to server and call callback when response is received
}

function infinite() {
    sendXHR('url/path', infinite);
}

infinite();

I assume here we would run out of stack space pretty quickly, so how can I do this (without blocking)?

The pattern of passing callbacks around rather than using return is particularly popular with node.js. How do people create infinite loops? I don't believe most JS engines do any kind of tail call optimisation.

6
  • 2
    That would not run out of stack space as when the callback is called the stack frames below it do not contain the stack of the previous infinite call. Commented Nov 17, 2012 at 4:49
  • @DanD. I tried it in Chrome by adding callback(); in sendXHR, and it reports Maximum call stack size exceeded after around 9500 iterations. Firefox also says too much recursion. Commented Nov 17, 2012 at 4:51
  • Well then maybe there's something interesting in the Send XMLHttpRequest to server and call callback when response is received part. Commented Nov 17, 2012 at 4:56
  • @muistooshort Sorry don't follow, am I missing something obvious? Commented Nov 17, 2012 at 4:58
  • I'm guessing your sendXHR function is using synchronous xhr then? Change this to asynchronous and execute the callback on the next tick. Commented Nov 17, 2012 at 4:59

1 Answer 1

10

If your ajax call is asynchronous, you do not run out of stack space because sendXHR() returns immediately after the ajax request is sent. The callback is then called some time later when the ajax response arrives. There is no stack build up.


If your ajax call is synchronous and you want to allow other events and what not to happen in the javascript environment, then you could so something like this:

function sendXHR(url, callback) {
    // Send XMLHttpRequest to server and call callback when response is received
}

function infinite() {
    sendXHR('url/path');
    setTimeout(infinite, 1);
}

infinite();
Sign up to request clarification or add additional context in comments.

3 Comments

His comments seem to prove that he does indeed run out of stack space, so it looks like he's sing synchronous XHR.
@SeanKinsey - since the OP was not clear about synch vs. async, I've now included answers for both.
Thanks, you are of course right.. there is no stack build up if it's asynchronous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.