Infinite loop with asynchronous callback pattern in javascript

Suppose I want to send an asynchronous AJAX request to the server, and when it answers, 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 that here we will end the stack space pretty quickly, so how can I do this (without locking)?

The callback pattern, rather than using return , is especially popular in node.js How do people create endless loops? I don't think most JS engines do any tail call optimization.

+6
source share
1 answer

If your ajax call is asynchronous, you will not end the stack space because sendXHR() returns immediately after sending the ajax request. The callback is then called some time after receiving the ajax response. No stacking.


If your ajax call is synchronous and you want to allow other events and that won't happen in the javascript environment, then you can do 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
source

All Articles