-1

I'm trying to make a series of calls to a web api, but the api is complaining about too many calls all at once, so I'm trying to set a delay. Here is some test code that I'm using:

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);
}

As I expected, the loop runs all the way through before the first timeout occurs, and, due to JS scoping rules, the output is:

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"]
...

How can I put a 100ms delay between each of my calls to the webapi in this loop while retaining the values I want to send in the headers, ie ["1"], ["2"], etc?

jaredad7
  • 998
  • 2
  • 11
  • 33
  • 2
    `var partitionKey` => `const partitionKey`. If you're able to use `let` and `const` why are you still using `var`? – zzzzBov Oct 18 '18 at 14:23
  • Instead of using setTimeout() did you think about using setInterval() ? That one will continue to execute the function untill you call clearInterval(). [Here is a link of how it works](https://www.w3schools.com/jsref/met_win_setinterval.asp) – cheikh ndiaye Oct 18 '18 at 14:28
  • @cheikhndiaye I believe Op doesn't want to re-call the same function but actually call different ones. Or perhaps the same function (making a network call) with a different parameter every time. In effect, he wants to stagger *different* network calls in order to not overwhelm the API, rather than just make *the same* call over and over again. You could, of course, have an interval that essentially picks up a different network call to make every time until it runs out of them and terminates but it seems weird to do that, as you know the sequence is different and finite. – VLAZ Oct 18 '18 at 14:35
  • @zzzzBov, that worked. Put it as an answer and I'll accept it. Thanks! – jaredad7 Oct 18 '18 at 14:48
  • That solution is already covered in the dupe. – VLAZ Oct 18 '18 at 14:49

2 Answers2

0

I suggest you try a recursive approach. Make your method call the api and once you get the response, call it recursively after a timeout period. Use a counter to set the max number of recursive calls.

Example:

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

function apiCall() {
  ajaxRequest().then(() => {
    currentCall ++;
    if (currentCall < maxCalls) {
      setTimeout(apiCall, timeout);
    }
  });
}
rubentd
  • 1,245
  • 11
  • 25
  • 1
    `setTimeout(apiCall, timeout);` is way shorter and simpler. Otherwise you wrapping the function call inside another function so you can execute the wrapper which executes the function. I think you can see the whole operation is unnecessarily complex in terms of execution. It also saves you two (or three) lines and makes this ever so slightly faster to read. – VLAZ Oct 18 '18 at 14:45
  • Good catch @vlaz I'm updating my example – rubentd Oct 18 '18 at 16:16
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++;
}
Takashi Harano
  • 294
  • 1
  • 3
  • 10