setTimeout in Node.js loop

后端 未结 8 1582
眼角桃花
眼角桃花 2020-12-06 05:16

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 l

8条回答
  •  独厮守ぢ
    2020-12-06 05:53

    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.

提交回复
热议问题