I'm using Nodejs to implement a web app. I'm having a list of objects and I want to call a 3rd party API for each of these objects. The problem is the api has rate limit so based on my calculation I have to call the api every 1.5 sec. I tried using setTimeout method but it doesn't work in for loop. I also looked into Cron module but it doesn't help me since I only want to call api once per object. Can anyone help me with this. here is my code in sever side :
for(var obj in list)
{
setTimeout(function() {
apicall();
}, 1500);
}
I'm using Nodejs to implement a web app. I'm having a list of objects and I want to call a 3rd party API for each of these objects. The problem is the api has rate limit so based on my calculation I have to call the api every 1.5 sec. I tried using setTimeout method but it doesn't work in for loop. I also looked into Cron module but it doesn't help me since I only want to call api once per object. Can anyone help me with this. here is my code in sever side :
for(var obj in list)
{
setTimeout(function() {
apicall();
}, 1500);
}
Share
Improve this question
edited Jun 5, 2015 at 22:43
Hirad Roshandel
asked Jun 5, 2015 at 22:39
Hirad RoshandelHirad Roshandel
2,1875 gold badges42 silver badges66 bronze badges
2
- Are you trying to do this from your node server or from the browser? – taylorc93 Commented Jun 5, 2015 at 22:41
- @taylorc93 from my node server – Hirad Roshandel Commented Jun 5, 2015 at 22:42
2 Answers
Reset to default 15The problem with for
loops, or any loops is, that they are usually fast. In fact, it takes about several microseconds to loop over the list
. This means that within a range of a few microseconds, you schedule several anonymous functions to be called after 1.5 seconds. This means that all the functions, even if delayed, will be fired almost all at once.
You need something that will cause the delays to increase over the course of the for
loop.
A most basic setup would be to use a current index of the array as a multiplier.
for(var i in list) { // list is an array, i is current index
setTimeout(function() {
apicall()
}, 1500 * i) // With each iteration, the delay increases
}
On a side note, in this basic example, you do not even need a closure:
setTimeout(apicall, 1500 * i)
You could make a variable that increments time on each pass of the loop so your timeout goes from 1500, 3000, 4500 on each loop adding 1500 each time the reason yours isn't working is because that loop is creating however many timeouts all within milliseconds of each other because they're asynchronous calls, so after like 1600 ms you have however many intervals all going off at once.