jQuery for 循环中的延迟队列
jQuery deferred queue in for loop
我有以下功能:
function getData(a,url) {
var deferreds = [];
var i = 1;
for (i = 1; i <= a.length; i++) {
var count = i;
var back = a[i]['link'];
var path = "http://example.com";
deferreds.push(
$.ajax({
url:path,
data:{back:back,link:url},
type:"POST",
async: true,
delay: count
}).done(function(data) {
//success function here
}));
}
return deferreds;
}
我的问题是如何将这个脚本做成运行一个队列,比如我有2000个请求,如何将它们一个一个地放入一个100个队列中?
也许是这样(当然是简化)
var completed = 0;
var limit_simultaneous = 100;
var total_requests = 2134 // Assign your var
function send_block() {
for (i = 0; i < limit_simultaneous; i++) {
$.ajax({
url:path,
data:{back:back,link:url},
type:"POST",
async: true,
}).done(function(data) {
completed++;
send_next_block();
//success function here
}));
}
}
function send_next_block()
{
if (completed == limit_simultaneous && total_requests > 0) {
total_requests = total_requests - completed;
if (total_requests < limit_simultaneous) {
limit_simultaneous = total_requests;
}
completed = 0;
// Fire again
send_block(); // Send another 100
}
}
希望对您有所帮助。
编辑 编辑以考虑请求总数。也许不是工作代码,但它是想法。
我有以下功能:
function getData(a,url) {
var deferreds = [];
var i = 1;
for (i = 1; i <= a.length; i++) {
var count = i;
var back = a[i]['link'];
var path = "http://example.com";
deferreds.push(
$.ajax({
url:path,
data:{back:back,link:url},
type:"POST",
async: true,
delay: count
}).done(function(data) {
//success function here
}));
}
return deferreds;
}
我的问题是如何将这个脚本做成运行一个队列,比如我有2000个请求,如何将它们一个一个地放入一个100个队列中?
也许是这样(当然是简化)
var completed = 0;
var limit_simultaneous = 100;
var total_requests = 2134 // Assign your var
function send_block() {
for (i = 0; i < limit_simultaneous; i++) {
$.ajax({
url:path,
data:{back:back,link:url},
type:"POST",
async: true,
}).done(function(data) {
completed++;
send_next_block();
//success function here
}));
}
}
function send_next_block()
{
if (completed == limit_simultaneous && total_requests > 0) {
total_requests = total_requests - completed;
if (total_requests < limit_simultaneous) {
limit_simultaneous = total_requests;
}
completed = 0;
// Fire again
send_block(); // Send another 100
}
}
希望对您有所帮助。
编辑 编辑以考虑请求总数。也许不是工作代码,但它是想法。