Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling function recursively at regular intervals

Tags:

node.js

So I was wondering what is a better way (in terms of stack growth and performance) to recursively call a function at regular intervals? For example, lets say I want to read file contents every 200 ms. I have the following two methods and was wondering if they are any different?

Method 1: Using plain ols setTimeout without 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);
})();

Method 2: Calling process.nextTick inside 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 () {
    process.nextTick(function () {
      loop();
    });
  }, 200);
})();

What I want to know is that adding process.nextTick inside setTimeout helps or not? Will calling the function inside process.nextTick will alleviate the stack usage or not?

like image 306
Nikhil Singh Avatar asked Jun 20 '12 06:06

Nikhil Singh


1 Answers

There is no recursion in the following simplified example:

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

test();

output (note that stack is not growing)

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)
like image 183
Andrey Sidorov Avatar answered Oct 26 '22 07:10

Andrey Sidorov