setTimeout in Node.js loop

后端 未结 8 1577
眼角桃花
眼角桃花 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 06:09

    I'm very late on the subject (as usual ...;) but the only way I found to loop requests to a slow time response API and getting responses without HTTP 504 is using promises.

    async function LoadDataFromAPI(myParametersArray) {
        for(var i = 0; i < myParametersArray.length; i++) { 
            var x = await RunOneRequest(myParametersArray[i]); 
            console.log(x); // ok
        }
    }
    

    The function called by the async function :

    function RunOneRequest(parameter) {
        return new Promise(resolve => {
            setTimeout(() => {
                request(parameter, (error, response, body) => {
                    // your request
                });
            resolve('ok);
            }, 2000); // 2 secs
        });
    }
    
    0 讨论(0)
  • 2020-12-06 06:11

    I might be late at the party but here is another (more readable) solution without the need to omit for loop.

    What your code does is creating 2000 (actually 1999) setTimeout objects that will call the makeRequest function after 1 second from now. See, none of them knows about the existence of the other setTimeouts.

    If you want them 1 sec apart from each other, you are responsible for creating them so.

    This can be achieve by using your counter (in this case i) and the timeout delay.

    for (var i = 1; i<=2000 && ok; i++) {
        var options = {
            host:'www.host.com',
            path:'/path/'+i
        };
    
        setTimeout(makeRequest(options, i), i * 1000); //Note i * 1000
    };
    

    The first timeout object will be set for 1 second from now and the second one will be set for 2 seconds from now and so on; Meaning 1 second apart from each other.

    0 讨论(0)
提交回复
热议问题