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