setTimeout in Node.js loop

setTimeout is non blocking, it is asynchronous. You give it a callback and when the delay is over, your callback is called.

Here are some implementations:

Using recursion

You can use a recursive call in the setTimeout callback.

function waitAndDo(times) {
  if(times < 1) {
    return;
  }

  setTimeout(function() {

    // Do something here
    console.log('Doing a request');

    waitAndDo(times-1);
  }, 1000);
}

Here is how to use your function:

waitAndDo(2000); // Do it 2000 times

About stack overflow errors: setTimeout clear the call stack (see this question) so you don't have to worry about stack overflow on setTimeout recursive calls.

Using generators (io.js, ES6)

If you are already using io.js (the "next" Node.js that uses ES6) you can solve your problem without recursion with an elegant solution:

function* waitAndDo(times) {
  for(var i=0; i<times; i++) {

    // Sleep
    yield function(callback) {
      setTimeout(callback, 1000);
    }    

    // Do something here
    console.log('Doing a request');
  }
}

Here is how to use your function (with co):

var co = require('co');

co(function* () {
  yield waitAndDo(10);
});

BTW: This is really using a loop ;)

Generator functions documentation.


You need something like this

var counter = 5;

function makeRequst(options, i) {
    // do your request here
}

function myFunction() {
    alert(counter);

    // create options object here
    //var options = {
    //    host:'www.host.com',
    //    path:'/path/'+counter
    //};
    //makeRequest(options, counter);

    counter--;
    if (counter > 0) {
        setTimeout(myFunction, 1000);    
    }
}

See also this fiddle

At the point of the alert(count); you can do your call to the server. Note that the counter works opposite (counting down). I updated with some comments where to do your thing.