Reputation: 157
I'm computing some heavy recursive function (let's say Fibonacci for the following code) I have two versions : - first one, vanilla recursive (uncommenting "if(false)" ) - the second one, using the process.nextTick every 5 calls in order to let other code run (uncommenting "if(n%5==0)" )
now running first one gets me a "RangeError: Maximum call stack size exceeded" while running the second one provides me with a nice "196418"
here's the code. Could you tell me what's going on, because I can't believe that process.nextTick is cleaning the stack.
'use strict';
function fibo_cb( n, cb ){ fibo_rec( n, (res) => cb( res ) ); }
function fibo_rec( n, ret ){
if( n<2 ){
ret( 1 );
} else {
let rr = (res_1) => { return (res_2) => ret(res_1+res_2) };
let r = (res_1) => fibo_rec( n-2, rr(res_1) );
//if(false){ //no tick
if(n%5==0){ //do tick, once every 5
process.nextTick( () => fibo_rec( n-1, r ) );
} else {
fibo_rec( n-1, r );
}
}
}
fibo_cb( 26, console.log );
Upvotes: 0
Views: 180
Reputation: 1347
The JavaScript code is executed by putting all the code in Call Stack by creating scopes at function level. Since JavaScript is single threaded(apart from Asynchronous tasks), starting from Global level each scope is put into the call stack one by one until it reaches all the functions. Once the function gets completed it is popped out of the Call Stack.
In case of Recursive Functions, for each recursive call a function is pushed to Call Stack. So when there are large number of recursive calls the Call Stack gets full since a maximum limit is fixed for Call Stack.
Any Asynchronous Task scheduled using process.nextTick
waits till call stack is empty and takes each callback from the Event Queue and pushes it to Call Stack. This happens repeatedly till all the recursive callbacks are finished.
Since Call Stack is emptied each time the is no "RangeError: Maximum call stack size exceeded" observed.
Upvotes: 1