setTimeout in Node.js loop

后端 未结 8 1601
眼角桃花
眼角桃花 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条回答
  •  Happy的楠姐
    2020-12-06 05:57

    Right now you're scheduling all of your requests to happen at the same time, just a second after the script runs. You'll need to do something like the following:

    var numRequests = 2000,
        cur = 1;
    
    function scheduleRequest() {
        if (cur > numRequests) return;
    
        makeRequest({
            host: 'www.host.com',
            path: '/path/' + cur
        }, cur);
    
        cur++;
        setTimeout(scheduleRequest, 1000)
    }
    

    Note that each subsequent request is only scheduled after the current one completes.

提交回复
热议问题