Search code examples
javascripttypescriptwebrequest

Node.js webrequest (http) stopping after several seconds


The code is working perfectly fine, when i am starting the request. It runs down, and starts multiple request at one after one, which is exactly, what i've been trying to do.

After several seconds, the script just stops itself. Which is not wanted. I dont exactly know why, so if anyone could help, I would apreaciate it.

var http = require('http');
var options = {
  host: '',
};
var i = 0;
var ii = 0;
callback = function(response) {
  i++;
  ii++;
  if (i == 100)
  {
    i = 0;
    console.log(ii);
  }
}
function get()
{
  http.request(options, callback).end();
  setTimeout(function(){ get() }, 10);
}
get();

Solution

  • Just put the get() function in a loop... That way, you can either controll, how many times it runs, or just let it run constantly, which is what I think you are aiming for.

    var = i;
    while (i < how long you want it to run) {
      http.request(options, callback).end();
      setTimeout(function(){ get() }, 10);
    i++;
    }
    
    
    OR
    
    while (true) {
      http.request(options, callback).end();
      setTimeout(function(){ get() }, 10);
    }