Search code examples
javascriptnode.jssettimeout

Unable to add a timeout in this node http get request


I have this code, where the function download should be called each 5 seconds, but it doesn't seem to work, since all the images are downloaded at the same time.

const download = function (uri, filename, callback) {
  request.head(uri, function (err, res, body) {
    request(uri).pipe(fs.createWriteStream(filename)).on('close', callback); 
   });
};

for (let i = 0; i < 100; i++) {
  setTimeout(function () {
    download(
      'https://www.thispersondoesnotexist.com/image', 
      `images/image${i}.jpg`,
      function () {
        console.log('done');
      });
    },
    5000
  )
}

Solution

  • Your setTimeout function is hard-coded with 5000. This means your loop is running from 0 to 99 and setting up 100 timeouts, each with a wait time of 5000. Since the loop is executed very quickly, the timeouts that get made also execute very close together.

    You need something like:

     setTimeout(function() {
       ...
       },
       5000 * i
     )
    

    This will spread the timeouts out from 0 * 5000 to 99 * 5000 milliseconds.