【问题标题】:Calling function recursively at regular intervals定期递归调用函数
【发布时间】:2012-06-20 16:43:05
【问题描述】:

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

方法一:使用无process.nextTick的普通ols setTimeout

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);
})();

方法二:在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 里面的函数会不会减少堆栈的使用?

【问题讨论】:

  • 不回答你,但你一定要把setTimeout放在你的readFile的回调中。
  • 我在这里看不到任何递归调用。当超时事件发生时调用循环调用,而不是从函数内部调用。在 loop() 返回之前不能调用它

标签: node.js


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2016-08-20
    相关资源
    最近更新 更多