user482594
user482594

Reputation: 17486

How can I prevent node program from stop running?

I see many applications that uses node runs forever.

Therefore, I tried using setInterval method, which I assumed it will let it run forever, but apparently it doesn't.

var request = require('request');

var queue = function(item) {
  request({
    uri: 'http://www.google.net'
  },
  function(error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body) // Print the google web page.
    }
  })
};
setInterval(queue("google"),1000); //do this every 1 second.

When I run above program, it stops after a second.

How can I can modify above codes to keep it running if I run it with node?

Upvotes: 1

Views: 593

Answers (3)

gwest7
gwest7

Reputation: 1653

You have to assign setInterval to a local variable.

setInterval(function(){},1000);

will stop.

var timer = setInterval(function(){},1000);

will not.

Upvotes: 2

neeebzz
neeebzz

Reputation: 11538

a much better solution is using the npm: forever

Upvotes: 2

alessioalex
alessioalex

Reputation: 63683

Actually you have a bug in your code:

setInterval(queue("google"),1000); //do this every 1 second.

Instead of passing a function above as the first parameter, you are passing the result of executing a function.

So either do setInterval(queue, 1000) or do the following if you want multiple params:

setInterval(function() {
  queue(how_many_params_you_want);
}, 1000);

Upvotes: 2

Related Questions