I've read this nice doc guide: https://nodejs.org/en/docs/guides/dont-block-the-event-loop/
And in some part of that article it's being said regarding to complex calculations without blocking the Event Loop:
Suppose you want to do complex calculations in JavaScript without blocking the Event Loop. You have two options: partitioning or offloading. You could partition your calculations so that each runs on the Event Loop but regularly yields (gives turns to) other pending events.
And they gave as an example this code example to calculate the avg of 0 + 1 + 2 + ... + n :
function asyncAvg(n, avgCB) {
// Save ongoing sum in JS closure.
var sum = 0;
function help(i, cb) {
sum += i;
if (i == n) {
cb(sum);
return;
}
// "Asynchronous recursion".
// Schedule next operation asynchronously.
setImmediate(help.bind(null, i+1, cb));
}
// Start the helper, with CB to call avgCB.
help(1, function(sum){
var avg = sum/n;
avgCB(avg);
});
}
asyncAvg(n, function(avg){
console.log('avg of 1-n: ' + avg);
});
My questions are:
- According to this doc link: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick
The setImmediate will be executed If the poll phase scripts have been scheduled by setImmediate(), then the event loop will end the poll phase and continue to the check phase to execute those scheduled scripts.
but if we are in the recursive step:
function help(i, cb) {
sum += i;
if (i == n) {
cb(sum);
return;
}
// "Asynchronous recursion".
// Schedule next operation asynchronously.
setImmediate(help.bind(null, i+1, cb));
}
then the poll should be empty but the setImmediate command, and therefore it should keep running the recursive, so how would it give opportunity to other code to be executed meanwhile? in terms of event-loop scheduling.
- Why for really big
nthere isn'tRangeError: Maximum call stack size exceedederror, but if I change this line:
setImmediate(help.bind(null, i+1, cb));
to this line:
help(i+1, cb);
then the error RangeError: Maximum call stack size exceeded pops up. I mean, using the setImmediate should anyway keep the functions stack caused by the recursive, no?