【发布时间】:2015-09-08 08:00:20
【问题描述】:
我有一个进度条,我在多次迭代的循环中更新。
https://jsfiddle.net/k29qy0do/32/ (在单击开始按钮之前打开控制台)
var progressbar = {};
$(function () {
progressbar = {
/** initial progress */
progress: 0,
/** maximum width of progressbar */
progress_max: 0,
/** The inner element of the progressbar (filled box). */
$progress_bar: $('#progressbar'),
/** Set the progressbar */
set: function (num) {
if (this.progress_max && num) {
this.progress = num / this.progress_max * 100;
console.log('percent: ' + this.progress + '% - ' + num + '/' + this.progress_max);
this.$progress_bar.width(String(this.progress) + '%');
}
},
fn_wrap: function (num) {
setTimeout(function() {
this.set(num);
}, 0);
}
};
});
$('#start_button').on('click', function () {
var iterations = 1000000000;
progressbar.progress_max = iterations;
var loop = function () {
for (var i = 1; i <= iterations; i++) {
if (iterations % i === 100) {
progressbar.set(i); //only updates the progressbar in the last iteration
//progressbar.fn_wrap(i); //even worse, since no output to the console is produced
}
}
}
//setTimeout(loop, 0);
loop();
});
控制台按预期迭代更新。 但是,进度条没有更新。
问题是浏览器窗口似乎“挂起”,直到循环结束。 只更新控制台,不更新进度条。
我已尝试在多个位置添加 setTimeout,如下所示。 但这只会让事情变得更糟,因为我什至没有让控制台在执行循环时输出进度。
【问题讨论】:
-
你的索引值的范围是多少?您是否打算除以 100 作为设置值的一部分?如果是这种情况,您可能会尝试使用十进制值设置进度条,但您已经解释过它可以处理 0 到 100 之间的整数。
-
这只是一个简化。我可以在控制台输出中看到使用正确的值调用进度条。我已经用
my_progressbar_element.innerHTML = 'update';替换了循环中的整个代码。仅在循环完成后才显示此文本。 -
您的 div 的宽度正在更新为控制台值。只需在进度条 div 中添加 background-color:red 即可查看。
-
@blue 不,这不是问题所在。循环运行时,DOM 更新被阻止。我需要想办法解决这个问题。
-
真实应用中进度更新如何?
标签: javascript jquery css progress