I'm trying to write a Node module running some code every second:
function worker() {
}
worker.prototype.process = function(callback) {
console.log("doing the job");
callback();
}
worker.prototype.query_process = function(callback) {
console.log("query_process called");
this.process(function() {
console.log("Process callback called");
setTimeout(function() { this.query_process }, 1000);
});
}
worker.prototype.start = function() {
this.query_process();
}
module.exports = worker;
I'm using it this way:
var worker = require('./lib/worker');
var worker = new worker();
worker.start();
Here is the output when running the script:
& node workerTest.js
query_process called
doing the job
Process callback called
Why is this not running in an infinite loop
EDIT1
Adding parentheses after method call
setTimeout(function() { this.query_process() }, 1000);
but now got this error:
/Users/dhrm/Development/project/lib/worker.js:14
setTimeout(function() { this.query_process() }, 1000);
^
TypeError: undefined is not a function
at null._onTimeout (/Users/dhrm/Development/project/lib/worker.js:14:32)
at Timer.listOnTimeout (timers.js:110:15)
setTimeout(function() { this.query_process }, 1000);
You don't call this.query_process again. Add parentheses after it to call the function.
Response to edit:
You also need to save the context for use in the callback:
worker.prototype.query_process = function(callback) {
var me = this;
console.log("query_process called");
this.process(function() {
console.log("Process callback called");
setTimeout(function() { me.query_process() }, 1000);
});
}