-2

I want to call an API every 2 seconds in a loop. How can i achieve this?

var letterArray = ['a', 'b', 'c'];
for (var j = 0; j < letterArray.length; j++) {
    $timeout(callApi(letterArray[j]), 2000);
}

function callApi(searchInput) {
    var request = {
        // 
        url: 'https://someApi/search?name=' + searchInput,
        method: 'GET',
        headers: {
            'Authorization': 'abc'
        }
    };
    $http(request).then(onComplete, onError);
}
theking963
  • 2,223
  • 7
  • 28
  • 42

1 Answers1

1

use $interval instead of $timeout and remove that loop, use a variable to keep track. Remember to dispose and cancel interval when scope disposes.

var letterArray = ['a', 'b', 'c'];

var inr = $interval(function(){
    var search = letterArray.shift();
    if(!search && inr) {
          $interval.cancel(inr);
          inr = null;
    }
    callApi(search);
}, 2000);

function callApi(searchInput) {
    var request = {
        // 
        url: 'https://someApi/search?name=' + searchInput,
        method: 'GET',
        headers: {
            'Authorization': 'abc'
        }
    };
    $http(request).then(onComplete, onError);
}

on that note, you may also want to cancel interval on exception with api or any scope dispose etc.

Axar
  • 521
  • 1
  • 3
  • 11
  • Can't remove the loop. I need to call the same api with multiple search criteria. – theking963 Jun 25 '18 at 19:30
  • So let me get this straight, you want to call the api with some search criteria off an array every 2 seconds ? You can sitll use $interval for that since, you're not really doing anything with results so no need for a chain. Use some var as counter and cancle the interval once you're done. Youre not really achieving anything at all by doing this, except maybe dont send all quests at onces. If you're trying to achieve more than this, you may need to look at promises and chain/sequence promises. – Axar Jun 25 '18 at 19:35
  • I am doing something with the result but the api throws an error if i send too many requests at once so I need a delay between each API call. – theking963 Jun 25 '18 at 19:41
  • The proper way to do this is to use chained promises with timeout; however, the $interval solution can still work here. Looks like someone posted an reference to a solution using $interval in comment. – Axar Jun 25 '18 at 19:44
  • How can I pass an argument in the function using `$interval`. – theking963 Jun 25 '18 at 19:49