When I run my code, Node.js throw "RangeError: Maximum call stack size exceeded"
exception caused by too much recursion calls. I tried to increase Node.js stack-size by sudo node --stack-size=16000 app
, but Node.js crash without any error message. When I run this again without sudo, then Node.js print 'Segmentation fault: 11'
. Is there a possibility to solve this without removing recursion call?
Thanks
You should wrap your recursive function call into a
setTimeout
,setImmediate
orprocess.nextTick
function to give node.js the chance to clear the stack. If you don't do that and there are many loops without any real async function call or if you do not wait for the callback, your
RangeError: Maximum call stack size exceeded
will be inevitable.There are many articles concerning "Potential Async Loop". Here is one.
Now some more example code:
This is right:
Now your loop may become too slow, because we loose a little time (one browser roundtrip) per round. But you do not have to call
setTimeout
in every round. Normally it is o.k. to do it every 1000th time. But this may differ depending on your stack size: