У меня есть индикатор выполнения, который я обновляю в цикле многих итераций.
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, как предлагается ниже, в нескольких местах. Но это только ухудшает ситуацию, потому что я тогда даже не получаю консоль для вывода прогресса при выполнении цикла.