Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  62] [ 3]  / answers: 1 / hits: 7608  / 10 Years ago, sun, august 10, 2014, 12:00:00

I am using a service to replace the words of an article with synonyms, the API of the service has a limit of 60 requests per minute. I have two functions, the first one get the article and split it into an Array, then calls the other to replace the words, I tried to do that by setting timeout to the second so it will be called first and then after 60 seconds, and then after 120 secs... so every minute I will call the service at most 60 times.



generateArticle : function(data){ 
Art.words = data.split( );
for(var j=0; j<Art.words.length/60; j+=1){
setTimeout(Art.generateSector(j*60),j*60000);
}
},

generateSector : function(position){
var count = 0;
for(var i=position; i<Art.words.length; i+=1){
if(Art.words[i].length > 3 && isNaN(Art.words[i]) && count < 60){
Art.findsimilarword(Art.words[i],i);
count++;
}
}
},


but what is happening is that the second function is called immediately, so in an article with 400 words the first 60 words will be replaced correctly but for the rest 340 words I am getting an error 429 (Too Many Requests) . Am I using the setTimeout with a wrong way? Can someone explain to me why this is happening?


More From » javascript

 Answers
1

This code:



setTimeout(Art.generateSector(j*60),j*60000);


calls Art.generateSector immediately, passing in j*60, and then takes its return value and passes it to setTimeout, exactly the way foo(bar()) calls bar and passes its return value into foo.



To schedule a call to the function, you pass in a function reference. In your case, you can probably use Function#bind:



setTimeout(Art.generateSector.bind(Art, j*60),j*60000);


Function#bind returns a new function that, when called, will call the original with the given value as this (in our case, Art) and any additional arguments you provide.






Function#bind is an ES5 feature. If you have to support really old JavaScript engines like the one in IE8, this feature can be shimmed (polyfilled). Search for function bind shim or function bind polyfill to find multiple options.


[#43231] Friday, August 8, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 3 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;