The javascript below accomplishes the following (this is for a node.js COMET application):
- Request is made to the server and held until the server has something to
return. - Once the request returns the data is processed and another
request is immediately made within the callback function of the
success event. - If a timeout occurs (the server had nothing to return within the time frame)
another request is made within the callback function of the error event.
My concern (which I believe is valid) is that the requests are continually added to the callstack, much like a recursive function that never ends. After a while, it results in the browser eventually crashing and becoming unresponsive (at least I think this is the cause).
How can I accomplish the same thing and avoid this problem?
function GetData(){
$.ajax({
url: "admin.html",
type: "POST",
dataType: "json",
contentType: 'text/json',
data: JSON.stringify({
cmd: "getData"
}),
timeout: (60 * 1000),
success: function(data, textStatus, jqXHR){
UpdateScreen(data);
GetData();
},
error: function(jqXHR, textStatus, errorThrown){
if(textStatus == "timeout"){
GetData();
}
}
});
}
No, I’m pretty sure you are OK. The ajax event is asynchronous, so the
GetDatafunction will finish and the browser will wait for events, before it callsGetDataagain from the success handler.Think of it as the GetData function just defining what to do, not actually doing it. Then it finishes executing (and clears the stack) and browser does those actions.