使用$ .when()。在循环中完成多个ajax调用之间的延迟

时间:2014-08-27 11:39:20

标签: jquery ajax jsonp delay

我试图在$ .when()。done()中的多组ajax调用之间引入延迟,这是在循环中完成的。我在哪里以及如何做到这一点?

var productURLs = [
                   "&wProd1", "&cProduct1",
                   "&wProd2", "&cProduct2",
                   "&wProd3", "&cProduct3"
                  ];

var getProduct = function(cwFlag, product) {

    api = "azqhb4pw";
    if (cwFlag == "w") { api = "60n2f9jg" }
    var urlAPI = "https://www.klabk.com/api/" + api + "?apikey=t5uSSkXLf0xY9UeuepOCTzQGfD3dB7jy" + product;

    return $.ajax({
        type: "GET",
        url: urlAPI,
        timeout: 2000, //*** this doesn't work
        dataType:"jsonp"
        //**** I also tried 'complete' and a delay here but didn't work ****
    })
}

function getBoth(cProduct, wProduct) {

        // Two ajax requests 
        $.when( getProduct("c", cProduct), getProduct("w",wProduct)).done(function (c_data, w_data) {

        var allData = [].concat(c_data[0]).concat(w_data[0]);
        //do stuff with jsonp data returned from both functions
        //...

        });

}

//loop through a product array and make the ajax calls with two variables
for (var i = 0; i < productURLs.length; i+=2) {

    getBoth(productURLs[i], productURLs[i+1]);
    //**** need to put a delay here before the 
    //**** next set of ajax calls, settimeout around 
    //**** this doesn't work either

};

1 个答案:

答案 0 :(得分:1)

我不确定这是不是你想要的。这将运行getBoth函数,每个函数的延迟为1秒。

var interval = setInterval(doAjax, 1000);
var count = 0;
function doAjax(){
    getBoth(productURLs[count], productURLs[count+1]);
    count = count+2;
    if(count>=productURLs.length){
        clearInterval(interval);
    }
}