Reputation: 21
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++;
});
Upvotes: 1
Views: 2410
Reputation: 32145
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.
Upvotes: 6