这是一个我现在已经挣扎了一段时间的问题。我已经实现了HTML5 progress
元素,如下所示:
<progress id="progress" value="0" max="100"></progress><output class="percent" id="percent">0</output><span class="prozent">%</span>
假设我在JS循环中更新了progress
和percent
的值:
i = 0;
pBar = document.getElementById('progress');
pBar.value = i;//start at 0%
percent = 1;//set target for next progress bar update in %
//DO
do {
//IF(i > i_max) EXIT
//CALL VERLET
VERLET(i, x, v, a, time, const0, gamma, A_o, omega, dt);
x_plot[i] = [time[i], x[i]];
v_plot[i] = [time[i], v[i]];
a_plot[i] = [time[i], a[i]];
//i = i + 1
i = i + 1;
if (parseInt(i / i_max * 100, 10) === percent) {
pBar.value = percent;//update progress bar
document.getElementById('percent').innerHTML = percent;
percent = percent + 1;
}
//END DO
} while (i < i_max);
这是我脚本的相关部分。 请假设所有变量都已正确声明和初始化,并且整个脚本都是linted。可以找到页面草稿here。
我不明白为什么progress
和output
元素的值在计算完成之前不会更新。或者这似乎发生了。 IE11(?)似乎在最初加载页面时会显示一些更新,但在没有重新加载的情况下再次更新进度条以进行新计算。
Here是类似的东西,但没有使用这种现代方法。我已经尝试了this示例工作,没有成功。 This例子,虽然我认为写得更好,但可能会对这个问题有所了解。
这是超时问题吗?有一个简单的jQuery方法我可以使用吗?任何关于这个问题的反馈都将不胜感激。
答案 0 :(得分:1)
作为@epascarello says,您无法在while
循环中更新DOM。
用间隔更新它:
var interval = setInterval(function () {
VERLET(i, x, v, a, time, const0, gamma, A_o, omega, dt);
x_plot[i] = [time[i], x[i]];
v_plot[i] = [time[i], v[i]];
a_plot[i] = [time[i], a[i]];
i = i + 1;
if (parseInt(i / i_max * 100, 10) === percent) {
pBar.value = percent;//update progress bar
document.getElementById('percent').innerHTML = percent;
percent = percent + 1;
}
if (i < i_max) {
clearInterval(interval);
}
}, 100);
答案 1 :(得分:0)
您无法在单个循环中执行此类操作。
循环将一直运行直到它结束,并且您只能在完成操作时看到结果。
对于这类问题,你应该采用异步方式。
function updateDom() {
// do stuff
setTimeout(updateDom, 500);
}
setTimeout(updateDom, 500);
答案 2 :(得分:0)
这是我如何让我的进度条动画:
<强> HTML 强>
<progress id="progress" value="0" max="100"></progress><output class="percent" id="percent">0</output><span class="prozent">%</span>
<强> JS 强>
start = new Date().getTime();
//do stuff
end = new Date().getTime();
t = (end - start);
document.getElementById('progress').value = 0;
document.getElementById('percent').innerHTML = 0;
if (parseInt(t / 100.0, 10) <= 1) {
t = 1;//minimum update interval in ms
} else {
t = parseInt(t / 100.0, 10);//actual update interval in ms
}
go = setInterval(animate, t);
value = 0;
max = 100;
go = 0;
function animate() {
if (value >= max) {
clearInterval(go);
return;
}
value += 1;
document.getElementById('progress').value = value;
document.getElementById('percent').innerHTML = value;
if (value === max) {
clearInterval(go);
}
}
当页面通过<body onload="amp()">
加载或用户<input type="number" name="theta0" id="theta0" value="0.1" min="0.0" max="1.6" step="0.1" onchange="amp()">
提示时,可以调用此脚本。如您所见,更新间隔与以ms为单位的CPU时钟时间相关联,因为在while
循环中我无法更新DOM。它很笨重但是很有效。