繁体   English   中英

设置超时以限制 http 请求

[英]setTimeout to throttle http request

我有一组大数组,getUser 是一种调用 api 的方法。如何每 5 秒调用一次 api? 因为现在 api 不允许每秒 x 个请求。

myarr 有大约 100 个项目。

myarr.forEach(id => {
   getUser(id).then(resp => {})
})

只需使用setInterval并在完成后将其清除。

let i = 0;

const timeId = setInterval(() => {
  getUser(myArr[i++]).then(...);
  i >= myArr.length && clearTimeout(timeId);
}, 5000);

使用队列将其从数组中弹出。

通话结束后 5 秒

var items = [1,2,3,4,5,6];

function fetchNext () {
  var currentData = items.shift();
  getUser(currentData)
    .then(resp => {
      if (items.length) {
        window.setTimeout(fetchNext, 5000);
      }
    })
}

通话间隔 5 秒

var items = [1,2,3,4,5,6];

function fetchNext () {
  var currentData = items.shift();
  getUser(currentData)
    .then(resp => {
    })
  if (items.length) {
    window.setTimeout(fetchNext, 5000);
  }
}

命中 api 的示例:

 function getUser(x) { return fetch('https://randomuser.me/api/?results=x').then((response) => response.json()) } var items = [1, 2, 3, 4, 5, 6]; function fetchNext() { var currentData = items.shift(); getUser(currentData).then(resp => { console.log(resp.results[0].name.first) }) if (items.length) { window.setTimeout(fetchNext, 5000); } } fetchNext()

您可以使用循环和setTimeout ,根据当前索引增加超时持续时间。

const arr = [1, 2, 3, 4, 5, 6, 7]

arr.forEach((num, index) => {
  setTimeout(() => {
    mockApiCall(num).then(console.log)
  }, index * 5000) // Increase timeout duration by 5 seconds for each element
})

// Emulate the HTTP call, replace this with your API call
function mockApiCall(number) {
  return new Promise(resolve => {
    resolve(`Sample result from api/${number}`)
  })
}

请注意,这是非常基本的,没有考虑错误处理、重试、退避等。

暂无
暂无

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

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