0

I need to call an API in a delay of 1 second between each call. I have this code in which the timeout doesn't work:

  for(var i=0; i < contentSize; i++){
    var content = contentArray[i];
    var j = table[i]; 
    var thisColumn = document.getElementById(j);
    if(content.includes('dl-media')){//content is image
      setTimeout(function() {evaluateImage(content, thisColumn); }, 2000);
    }
    else if(content != ""){//content is text
         // evalutaeText(language, content, thisColumn);
      }
    else{
          $(thisColumn).replaceWith("<div>No content</div>");
        }
  }

Only if I set the timeout on the for loop then there is a delay of 2 seconds between one call to another, but then it takes too long and I only need the delay on the function call. The function that I'm calling executes an Ajax call:

$.ajax({
              url: "https://westus.api.cognitive.microsoft.com/contentmoderator/moderate/v1.0/ProcessImage/Evaluate?" + $.param(params),
              beforeSend: function(xhrObj){
                  // Request headers
                  xhrObj.setRequestHeader("Content-Type","application/json");
                  xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","bd43e");
              },
              type: "POST",
              // Request body
              data: "{'DataRepresentation':'URL', 'Value':" + content +"}",
          })
          .done(function(data) {
              $(thisColumn).replaceWith("<div id="+thisColumn.value+">" + data.AdultClassificationScore +"<br>"+ data.RacyClassificationScore + "</div>");
          })
          .fail(function() {
              $(thisColumn).replaceWith("<div id="+thisColumn.value+">Failed</div>");
          });
Freckles
  • 71
  • 8
  • 2
    Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Teemu Jan 15 '17 at 15:51

1 Answers1

0

Your code schedules contentSize number of requests to be executed after 2 seconds of the start of the for cycle. You probably want to send one request in each two seconds:

var requestsSent = 0;
var requestsHandled = 0;

setInterval(function() {
    if (requestsSent > requestsHandled) {
        //The previous request was not completed yet, so let's wait
        return;
    }
    requestsSent++;
    $.ajax({
              url: "https://westus.api.cognitive.microsoft.com/contentmoderator/moderate/v1.0/ProcessImage/Evaluate?" + $.param(params),
              beforeSend: function(xhrObj){
                  // Request headers
                  xhrObj.setRequestHeader("Content-Type","application/json");
                  xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","bd43e");
              },
              type: "POST",
              // Request body
              data: "{'DataRepresentation':'URL', 'Value':" + content +"}",
          })
          .done(function(data) {
              requestsHandled++;
              $(thisColumn).replaceWith("<div id="+thisColumn.value+">" + data.AdultClassificationScore +"<br>"+ data.RacyClassificationScore + "</div>");
          })
          .fail(function() {
              $(thisColumn).replaceWith("<div id="+thisColumn.value+">Failed</div>");
          });
}, 2000);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Yes, I want to send one request in each 2 seconds. Unfortunately, this doesn't delay the calls either.. all the requests are sent at the same time :( – Freckles Jan 15 '17 at 16:16
  • @freckles.karin have you checked your dev tools and inside that the Network tab to be sure? – Lajos Arpad Jan 15 '17 at 16:25
  • Some are delayed and some are running at the same time which causes an error. https://www.screencast.com/t/KxynrUmUS – Freckles Jan 15 '17 at 16:41
  • The code in my answer makes sure that it only sends one request at a time. Note that when requestsSent > requestsHandled nothing happens and the increase of requestsHandled is waited for which happens when the request is done. Therefore I think you might be calling this code at several different places, or your Javascript is cached in your browser, or you have another code sending requests as well. – Lajos Arpad Jan 15 '17 at 16:45