For循环期间的JavaScript暂停

时间:2014-08-12 14:23:08

标签: javascript for-loop settimeout sleep

我有以下功能,并且在每次2秒请求后尝试添加暂停,但未成功,不会超过RPM阈值。

<cfoutput>
<script type="text/javascript" language="JavaScript">

    // Convert ColdFusion variable to JS variable
    #ToScript(Variables.resourceIds, "jsList")#

    // Split list
    var list = jsList.split(",");

    // Loop through list
    for (var i=0; i<list.length; i++) {         
        var pricingSearch = new XMLHttpRequest();
        pricingSearch.open("GET", "doPricing.cfm?ID=" + list[i], false);
        pricingSearch.onload = function (e) { };
        pricingSearch.onerror = function (e) { };
        pricingSearch.send(null);
        console.log('Searching for Id ' + list[i] + '...');
        setTimeout(function() {
            // Wait for a couple seconds
        }, 2000);
        if (i == list.length) {
            console.log('All done!');
        }           
    }
</script>
</cfoutput>

这似乎没有做任何事情,因为循环尽可能快地完成。

我甚至尝试过调整代码:

for (var i=0; i<list.length; i++) {         
    setTimeout(function(list,i) {               
        var pricingSearch = new XMLHttpRequest();
        pricingSearch.open("GET", "doPricing.cfm?ID=" + list[i], false);
        pricingSearch.onload = function (e) { };
        pricingSearch.onerror = function (e) { };
        pricingSearch.send(null);
        console.log('Searching for Resource Id ' + list[i] + '...');
        if (i == list.length) {
            console.log('All done!');
        }
    }, 2000);       
}

但这也行不通:(

是否有其他人知道我可以用来实现此目的的任何其他方法?

由于

1 个答案:

答案 0 :(得分:2)

您可以使用延迟参数,因此您可以延迟每个请求2秒。后来。但是如果请求有限制,您可以尝试在完成上一个请求时调用下一个请求。

var delay = 2000;
for (var i=0; i<list.length; i++) {         
    setTimeout(function(list,i) {               
        var pricingSearch = new XMLHttpRequest();
        pricingSearch.open("GET", "doPricing.cfm?ID=" + list[i], false);
        pricingSearch.onload = function (e) { };
        pricingSearch.onerror = function (e) { };
        pricingSearch.send(null);
        console.log('Searching for Resource Id ' + list[i] + '...');
        if (i == list.length) {
            console.log('All done!');
        }
    }, delay);
    delay += 2000;
}


//alternative
function callRequest(index){
        if (index == list.length) {
            console.log('All done!');
            return;
        }
        var pricingSearch = new XMLHttpRequest();
        pricingSearch.open("GET", "doPricing.cfm?ID=" + list[index], false);
        pricingSearch.onload = function (e) { callRequest(index+1); };
        pricingSearch.onerror = function (e) { console.log('error on index:' + index);callRequest(index+1)};
        pricingSearch.send(null);
        console.log('Searching for Resource Id ' + list[index] + '...');


}
callRequest(0);