Delay between Nodejs api calls

I am using Nodejs to implement a web application. I have a list of objects, and I want to call a third-party API for each of these objects. The problem is that api has a speed limit, so based on my calculation, I have to call api every 1.5 seconds. I tried using the setTimeout method, but it does not work in a for loop. I also studied the Cron module, but this does not help me, since I want to only call api on the object once. Can anyone help me with this. here is my code aside:

for(var obj in list)
{
      setTimeout(function() {
          apicall();
                }, 1500);
}
+4
source share
2 answers

for , . list . , 1,5 . , , , .

-, for.

- .

for(var i in list) { // list is an array, i is current index
  setTimeout(function() {
    apicall()
  }, 1500 * i) // With each iteration, the delay increases
}

:

setTimeout(apicall, 1500 * i)
+6

, , - 1500, 3000, 4500 , 1500 , , , , - , , , 1600 , , .

+1

All Articles