Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

setTimeout in Node.js loop

setTimeout in Node.js loop


I'm a bit confused as to how setTimeout works. I'm trying to have a setTimeout in a loop, so that the loop iterations are, say, 1s apart. Each loop iteration makes an HTTP request and it seems like the server on the other end can't handle that many requests in such a short time span.

for (var i = 1; i

Why does this not work and how can I achieve this?

Thank you

Problem courtesy of: glasspill


You need something like this

var counter = 5;

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

function myFunction() {

    // create options object here
    //var options = {
    //    host:'',
    //    path:'/path/'+counter
    //makeRequest(options, 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.

Solution courtesy of: bart s


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

setTimeout in Node.js loop


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription