我有一些嵌套的 for 循环需要几秒钟才能运行,所以我想显示一个进度条。问题是这不是一个本质上的异步过程,它是一个带有 3 个嵌套循环的代码块。我尝试了多种方法来屈服以呈现页面,有或没有
requestAnimationFrame()
,异步等待,以及带有等待...的异步生成器。下面的代码片段代表了我让它工作的唯一方法。
有更好的方法吗?例如,不涉及在动画回调中调用生成器函数的方法。
let val;
const progress = document.getElementsByTagName("progress")[0];
function run() {
val = 0;
requestAnimationFrame(animateProgress);
}
function animateProgress() {
const next = loop().next();
if (!next.done) {
progress.value = next.value;
frame = requestAnimationFrame(animateProgress);
}
}
function* loop() {
let i, j;
for (i = 0; i < 100; i++) {
for (j = 0; j < 100; j++) {
++val;
}
yield val;
}
}
* {
font-family:monospace;
font-size:1rem;
}
<button onclick="run()">Run</button>
<progress value="0" max="10000"></progress>
进度条有它自己的状态,所以你可以使用它。否则就使用全局变量。进度条知道它的最大值是多少,因此您不需要依赖生成器来“完成”。您所做的就是
requestAnimationFrame
的典型用法。
const progress = document.querySelector("progress");
function run() {
progress.value = 0;
requestAnimationFrame(animateProgress);
}
function animateProgress() {
const newVal = progress.value + 100;
progress.value = newVal;
if (newVal < progress.max) {
requestAnimationFrame(animateProgress);
}
}
* {
font-family:monospace;
font-size:1rem;
}
<button onclick="run()">Run</button>
<progress value="0" max="10000"></progress>