我想发送电子邮件至> 2000名获奖者。我发了一封发送50封电子邮件的ajax电话,我想重复一遍,直到所有电子邮件发送完毕。 PHP函数返回一个包含3个索引的数组,成功(计数成功邮件),失败(计数失败邮件)和完成(确定不再存在电子邮件)。所以,我收到电子邮件计数,我使用计数器(i)来确定发送的电子邮件数量。我希望在i> =计数时打破循环。这是我的代码:
function sendEmailStepByStep(imageAddress, counts) {
$(".feature div").append("<br />Please wait...<div class='feature_process'> </div>" + "<div class='feature_message'>Success: <span id='success_email'>0</span>, Failed: <span id='failed_email'>0</span></div>");
var i = 0;
timer = setTimeout(function () {
$.ajax({
type: "GET",
url: "",
dataType: 'json',
data: {
group: 'packages',
do :'emailPackageUsingAjax',
image: imageAddress,
num: i
}
}).done(function (response) {
console.log('success');
console.log(response);
$("#success_email").html(response.Success);
$("#failed_email").html(response.Failed);
i = i + response.Success + response.Failed;
if (i > counts || response.Finish == 'true') {
clearTimeout(timer);
}
}).fail(function (response) {
$(".feature_message").append(response.responseText);
console.log("error");
console.log(response);
clearTimeout(timer);
})
}, 1000);
}
为什么只召唤一次?
答案 0 :(得分:3)
我建议不要使用setTimeout或setInterval:
function sendEmailStepByStep(imageAddress, counts) {
$(".feature div").append("<br />Please wait...<div class='feature_process'> </div>" + "<div class='feature_message'>Success: <span id='success_email'>0</span>, Failed: <span id='failed_email'>0</span></div>");
var i = 0;
var mailer = function () { // Create internal function instead of timer
$.ajax({
type: "GET",
url: "",
dataType: 'json',
data: {
group: 'packages',
do :'emailPackageUsingAjax',
image: imageAddress,
num: i
}
}).done(function (response) {
console.log('success');
console.log(response);
$("#success_email").html(response.Success);
$("#failed_email").html(response.Failed);
i = i + response.Success + response.Failed;
if (i < counts && response.Finish != 'true') {
mailer(); // if count is less and not finished, invoke function again
}
}).fail(function (response) {
$(".feature_message").append(response.responseText);
console.log("error");
console.log(response);
})
};
mailer(); // First invocation of function
}
使用上述技术将确保仅在前一个批次完成时发送下一批,即使超过1秒,也会在超时时设置。