Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop with asynchronous callback pattern in javascript

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.

like image 953
Flash Avatar asked Nov 17 '12 04:11

Flash


1 Answers

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();
like image 70
jfriend00 Avatar answered Oct 23 '22 15:10

jfriend00