2017-01-15 53 views
0

我需要在每次調用之間的延遲1秒內調用API。我有這樣的代碼,其中超時不起作用:在函數調用之間設置超時

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

只有當我設置超時的for循環有2秒一個電話到另一個之間的延遲,但隨後的時間太長我只需要在函數調用中的延遲。 我正在調用該函數執行Ajax調用:

$.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>"); 
      }); 
+2

的可能的複製[JavaScript的閉包內環路 - 簡單實用的例子(http://stackoverflow.com/questions/750486/javascript-closure-inside-循環 - 簡單實用 - 示例) – Teemu

回答

0

你的代碼的時間表contentSize 2秒鐘的週期開始後,被執行的請求數。你可能想送在每兩個秒鐘就有一個要求:

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); 
+0

是的,我想每2秒發送一個請求。不幸的是,這不會延遲電話要麼..所有的請求同時發送:( – Freckles

+0

@ freckles.karin你檢查了你的開發工具,並在網絡標籤內確定? –

+0

有些延遲和一些正在運行在同一時間,這會導致一個錯誤。https://www.screencast.com/t/KxynrUmUS – Freckles

相關問題