以固定间隔递归调用函数

时间:2012-06-20 06:40:38

标签: node.js

所以我想知道什么是更好的方式(在堆栈增长和性能方面)以定期间隔递归调用函数? 例如,假设我想每200毫秒读取一次文件内容。我有以下两种方法,并且想知道它们是否有任何不同?

方法1:使用普通ols setTimeout而不使用process.nextTick

var fs = require('fs');
(function loop() {
  // Print to time to indicate something is happening
  console.log(new Date().toString());

  // Read a 51MB file
  fs.readFile('./testfile', function (err, data) {
    if (err) console.log(err);
  });

  // Call the same function again
  setTimeout(function () {
    loop();
  }, 200);
})();

方法2:在setTimeout

中调用process.nextTick
var fs = require('fs');
(function loop() {
  // Print to time to indicate something is happening
  console.log(new Date().toString());

  // Read a 51MB file
  fs.readFile('./testfile', function (err, data) {
    if (err) console.log(err);
  });

  // Call the same function again
  setTimeout(function () {
    process.nextTick(function () {
      loop();
    });
  }, 200);
})();

我想知道的是在setTimeout中添加process.nextTick有助于与否?调用process.nextTick里面的函数会不会减轻堆栈的使用?

1 个答案:

答案 0 :(得分:32)

以下简化示例中没有递归:

function test()
{
   console.trace();
   setTimeout(test, 1000);
}

test();

输出(注意堆栈没有增长)

Trace
    at test (/private/tmp/rec.js:3:12)
    at Object.<anonymous> (/private/tmp/rec.js:7:1)
    at Module._compile (module.js:449:26)
    at Object..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function._load (module.js:312:12)
    at module.js:487:10
    at EventEmitter._tickCallback (node.js:238:9)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)
Trace
    at Object.test [as _onTimeout] (/private/tmp/rec.js:3:12)
    at Timer.ontimeout (timers.js:101:19)