简体   繁体   English

循环nodejs的每次迭代延迟

[英]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. 这是我的代码,它在setTimeout函数等待大约x秒并一次运行所有迭代而无需等待之后,对于第一次迭代工作正常。

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. 好吧,您的超时使用的静态delay值为30000 ,所有迭代将使用该值,因此它们将在30秒后开始。

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. 我使用了一个数字数组并减少了延迟值以进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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