简体   繁体   中英

Delay in each iteration of loop nodejs

I want to wait on every iteration of the loop except the 1st one. This is my code which is working fine for 1st iteration after that setTimeout function wait for some x seconds and run all the iterations at once without wait.

Here is the code

var requests_made = 0;
drivers.forEach(function(driver) {
    if (requests_made == 0) {
        createUser(data);
    } else {
        setTimeout(function () {
            createUser(data);
        },30000);
    }
    requests_made++;
});

Well your timeout uses a static delay value wich is 30000 , which will be used by all the iterations, so they will all start after 30 seconds.

This delay should be dynamic and increase dynamically along with the iterated index, here's what you will need:

 var requests_made = 0; var drivers = [10, 50, 30, 40, 50]; drivers.forEach(function(driver, index) { if (requests_made == 0) { //createUser(data); console.log(index); } else { setTimeout(function() { //createUser(data); console.log(index); }, 1000 * index); } requests_made++; }); 

Note:

I used an array of numbers and reduced the delay value for testing purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM