Infinite loop with asynchronous callback pattern in javascript


Question

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.

1
6
11/17/2012 4:39:42 AM

Accepted Answer

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();
9
11/17/2012 4:59:45 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon