I am getting a "too much recursion" error. I will try to give a clear analog to my actual application where this problem is occurring.
Imagine that the app is trying call a webservice to get information about the contents of a very long freight train. There is so much information that we cannot simply invoke the webservice and tell it to send down everything all at once about every car in tthe entire train. Rather, we ask the webservice about each freight-car in turn, and when the info about a single boxcar is received, we update the page and then ask for the next car.
To keep the client responsive, we avoid a loop and use events with array.shift() instead:
We have an event:
$('body').bind('NextBoxCar', function( e, p) { getNexBoxCar(e,p); });
We have a function that removes the first boxcarid from the array and sends it to the webservice:
EDIT: BoxCarIds is not a global but inside a function
function() foo {
var BoxCarIds = [123, 222, 767, 1234, 9298, ... 999];
$('body').triggerHandler('NextBoxCar', BoxCarIds);
}
function getNextBoxCar(e, BoxCarIds) {
var id = BoxCarIds.shift();
// build an ajax request; omitted for brevity
$.ajax( {
.
. <snip>
.
success: function(data, textStatus, oHTTP ) {
UpdatePage(data, BoxCarIds);
}
});
}
When the data for the boxcar comes back from the webservice, the ajax success-handler invokes the following function, which updates the page and then fires the NextBoxCar event. I believe this is where the recursion problem is happening.
function UpdatePage(data, BoxCarIds) {
// update the page with data
.
. <snip>
.
// if there are still ids remaining in the array, we need to call the webservice again by firing the event
if (BoxCarIds.length > 0 ) {
$('body').triggerHandler('NextBoxCar', BoxCarIds);
}
}
How to avoid the recursion problem?
Thanks