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");
    }); 
2
  • 3
    Interesting question, but that's a really weird way to code it. Wouldn't a normal loop work better? Better yet, a POST request? Commented Apr 9, 2010 at 5:06
  • @deceze, the above is just a simplified code. And the business logic requires me to submit the data asynchronously one by one to the server like this (one data per request). I must not submit it as a bunch of array in a POST request as you suggested, and I must wait for the submission to complete before submitting another. Do you have cleaner way of doing this without recursion? Commented Apr 9, 2010 at 7:12

2 Answers 2

6

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();
Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

+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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.