Recursive code causes a stack overflow if the array list is too large. A solution

Source: Internet
Author: User

var list = readhugelist (); var function () {    var item = list.pop ();     if (item) {        //  Process the list item ...         Nextlistitem ();    }};

Potential stack overflows can be avoided by modifying the Nextlistitem function:
var list = readhugelist (); var function () {    var item = list.pop ();     if (item) {        //  Process the list item ...        SetTimeout (nextlistitem, 0);}    ;
The stack overflow is eliminated because the event loop manipulates recursion instead of the call stack. When Nextlistitem runs, if item is not empty, the timeout function (Nextlistitem) is pushed to the event queue and the function exits, so the air conditioning stack is cleared. When the event queue runs its timeout event and is made to the next item, the timer is set to call Nextlistitem again. Therefore, the method has no direct recursive invocation from beginning to end, so the call stack remains empty regardless of the number of iterations.

Recursive code causes a stack overflow if the array list is too large. A solution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.