views:

52

answers:

2

Why am I getting "too much recursion" error when I do the following?

    function sendTheNames() {

       alert("start submitting names..");

        return function (array) {

            var name = $(array.shift()).text();

            $.ajax({
                url: "test.jsp?name=" + name,
                complete: function () {
                    if (array.length > 0) {
                        return arguments.callee(array);
                    }
                }
            });
        };

    }

    $(document).ready(function () {

        var selectedNames = [];
        $('ul li input:checked').each(function () {
            selectedNames.push($(this).parent());
        });

        alert("begin");

        sendTheNames()(selectedNames);

        alert("done");
    }); 
+1  A: 

because arguments.callee in that context refers to complete: function () {...}

You are recursing without getting any closer to a terminal condition. Essentially

function complete() {
    if (array.length > 0) {
        return complete(array);
    }
}

to have it recur to some other function put this inside the function you want to recur to:

var outerCallee = arguments.callee;

and recur using

return outerCallee(array);
cobbal
+1 for answering the question spot on, very educational. Now I understand javascript a little better, this will surely come in handy down the road. I tested your solution and it works, but I accept deceze answer because it is more readable.
Rosdi
+2  A: 

If you absolutely need asynchronous, separate calls, at least do a little simpler recursion along the lines of this:

var selectedNames = ['Abe', 'Burt', 'Chris'];

function sendNames() {
    var name = selectedNames.shift();

    $.ajax({
        url: "test.jsp?name=" + name,
        complete: function () {
            if (selectedNames.length > 0) {
                sendNames();
            }
        }
    });
}

sendNames();
deceze
Still recursion, but more readable.. thanks.
Rosdi