如何在JavaScript中设置循环迭代之间的延迟?

时间:2018-10-18 14:21:09

标签: javascript for-loop delay

我正在尝试对Web api进行一系列调用,但是api一次抱怨太多调用,因此我尝试设置延迟。这是我正在使用的一些测试代码:

for(var i = 1; i <= 165; i++)
{
    var partitionkey = '["' + i + '"]';
    const options = {  
    url: 'https://mytech-lounge-metrics.documents.azure.com/dbs/metrics/colls/LoungeVisits/sprocs/calculateAverage',
    method: 'POST',
    headers: {
        'Authorization': 'authString',
        'x-ms-version': '2017-02-22',
        'x-ms-date': 'today',
        'Content-Type': 'application/json',
        'x-ms-documentdb-partitionkey': partitionkey
        }
    };
    setTimeout(function(){
        // Some Web API call would theoretically go in here
        console.log("Trying for partition " + partitionkey);
    }, i*100);
}

正如我预期的那样,循环一直持续到第一次超时发生之前,并且由于JS作用域规则,输出为:

Trying for partition ["165"]
Trying for partition ["165"]
Trying for partition ["165"]
Trying for partition ["165"]
Trying for partition ["165"]
Trying for partition ["165"]
Trying for partition ["165"]
Trying for partition ["165"]
...

在此循环中,如何在每次调用webapi的时间之间设置100ms的延迟,同时保留要在标头中发送的值,例如["1"]["2"]等?

2 个答案:

答案 0 :(得分:0)

我建议您尝试一种递归方法。让您的方法调用api,一旦获得响应,就在超时时间后递归调用它。使用计数器设置递归调用的最大数量。

示例:

let maxCalls = 165;
let currentCall = 0;
const timeout = 1000;

function apiCall() {
  ajaxRequest().then(() => {
    currentCall ++;
    if (currentCall < maxCalls) {
      setTimeout(apiCall, timeout);
    }
  });
}

答案 1 :(得分:0)

var i = 1;
function foo() {
    var partitionkey = '["' + i + '"]';
    var options = {  
        url: 'https://mytech-lounge-metrics.documents.azure.com/dbs/metrics/colls/LoungeVisits/sprocs/calculateAverage',
        method: 'POST',
        headers: {
            'Authorization': 'authString',
            'x-ms-version': '2017-02-22',
            'x-ms-date': 'today',
            'Content-Type': 'application/json',
            'x-ms-documentdb-partitionkey': partitionkey
        }
    };
    console.log("Trying for partition " + partitionkey);
    if (i < 165) {
        setTimeout(foo, 100);
    }
    i++;
}