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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With