6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nextTickで重い処理でもイベントループを止めない

6
Last updated at Posted at 2013-02-12

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
6
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?