我需要使用不同的“百分比”参数重复调用递归函数,以使它们连接在一起,成为前端的进度条。例如,我需要用这些百分比调用该函数五次:
progress(21); progress(42); progress(64); progress(85); progress(100);
我能够使进度条显示为(21, 42, 64, 85, 100)
,但是我希望每个函数调用的进度条都从(0-21, 22-42, 43-64, 65-85, 86-100)
开始。
如果在下一个函数调用之前未完成其段,也可以。例如0-18, 22-40, 43-56
等...
如果必须等到更高端直到下一个函数调用,也可以。例如,
0-21
(在下一个函数调用之前完成并等待),22-42, 43-64
等...
function progress(percent) {
console.log(percent);
$('.progress-bar span').css({
width: percent + '%'
});
$('.progress-percent-done').text(percent + '%');
var timeout = 500;
if (percent < 100) {
setTimeout(function () {
progress(percent);
}, timeout);
}
}
//excerpt showing how progress function is called
beforeSend: function () {
var batch_remainder = Math.max(0, ((batch_count + 1) * batch_size) - total_count);
var percent = Math.round(((((batch_count + 1) * batch_size) - batch_remainder) / total_count) * 100);
progress(percent);
...
答案 0 :(得分:0)
您可以通过使用promise实现此目的,如下所示:
function progress(percent) {
console.log(percent);
$('.progress-bar span').css({
width: percent + '%'
});
$('.progress-percent-done').text(percent + '%');
return new Promise(function(resolve) {
var timeout = 500;
if (percent < 100) {
setTimeout(function () {
percent++; // Increment percent
progress(percent);
}, timeout);
}
else {
resolve()
}
})
}
progress(21).then(function() {
return progress(42);
})
.then(function() {
return progress(64);
})
.then(function() {
return progress(85);
})
.then(function() {
return progress(100);
})