简体   繁体   English

如何使用setTimeout防止429(请求过多)错误

[英]How to prevent 429 (Too Many Requests) error using setTimeout

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. 我正在使用服务用同义词替换文章的单词,该服务的API每分钟限制60个请求。 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. 我有两个函数,第一个函数获取文章并将其拆分为一个Array,然后调用另一个函数替换单词,我试图通过将timeout设置为第二个来做到这一点,因此将首先调用它,然后在60秒后调用它,然后在120秒后...因此,每分钟我最多会致电60次服务。

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) . 但是发生的是第二个函数被立即调用,因此在一篇有400个单词的文章中,前60个单词将被正确替换,而对于其余的340个单词,我将收到错误429 (Too Many Requests) Am I using the setTimeout with a wrong way? 我是否以错误的方式使用setTimeout? Can someone explain to me why this is happening? 有人可以向我解释为什么会这样吗?

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 . 立即 调用 Art.generateSector ,传入j*60 ,然后获取其返回值并将其传递给setTimeout ,正是foo(bar()) 调用 bar并将其返回值传递给foo

To schedule a call to the function, you pass in a function reference. 要安排对该函数的调用,请传入一个函数引用。 In your case, you can probably use Function#bind : 在您的情况下,您可以使用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返回一个新的函数,调用它时,会调用原始的给定值作为this (在我们的情况下, Art ),你提供任何额外的参数。


Function#bind is an ES5 feature. Function#bind是ES5功能。 If you have to support really old JavaScript engines like the one in IE8, this feature can be "shimmed" ("polyfilled"). 如果必须支持真正的旧JavaScript引擎(例如IE8中的JavaScript引擎),则可以“填充”(“填充”)此功能。 Search for "function bind shim" or "function bind polyfill" to find multiple options. 搜索“函数绑定垫片”或“函数绑定polyfill”以找到多个选项。

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

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