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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With