0.9からはsetImmediate()を使うようですが。
(function total(i, res) {
if (i === 0) {
console.log(res);
}
res += i;
process.nextTick(function () {
total(--i, res);
});
})(100000, 0);
# 5000050000
nextTick付けないで100000で計算しようとすると
「RangeError: Maximum call stack size exceeded 」
と怒られるけど、nextTick()でやると怒られない。
ただ、こういうやり方はよくなくて、CPUヘビーな処理なら子プロセスとかでやった方がいい?
おまけ
フィボナッチ数列はこんな感じかな
var counter = 0,
total = 0;
(function fib(n) {
if (n < 2) {
total += 1;
return;
}
++counter;
process.nextTick(function () {
fib(n - 2) + fib(n - 1);
if (!--counter) {
console.log(total);
}
});
})(10);
# 121393