我需要在 javascript 的 for 循环中有一个进度条
for(index=0; index < 1000; index++){
// set progress bar value to index/1000 * 100 + '%'
}
我注意到我们可以将它放在 setInterval
函数中,但是运行 for 循环会花费更多时间。
那么有什么方法可以在不花费更多时间的情况下运行for循环并生成进度条吗?
最佳答案
So is there any way to run the for loop and generate the progress bar without cost more time?
MoSTLy no(见下文了解为什么“moSTLy”),你必须返回给浏览器(例如,通过 setTimeout
或 setInterval
)以便它可以更新页面显示,这确实会增加循环运行的时间。现在,通常如果您使用 0
的超时,浏览器将在 5 到 10 毫秒之间给您回电。所以称之为 10ms。在您的 1,000 周期循环中,您可能每 100 个周期产生一次(例如,10 次进度更新),这只会使总时间增加 100 毫秒左右。
FWIW,它看起来像这样(假设它是一个你正在循环的数组):
function loop(array, batchSize, callback) {
var index = 0;
doWork();
function doWork() {
var limit = Math.min(array.length, index + batchSize);
while (index < limit) {
// Do something with array[index]
}
if (limit < max) {
setTimeout(doWork, 0);
}
else {
callback(); // Done
}
}
}
使用:
loop(someArray, 100, function() {
// Done
});
为什么“大部分”不是:关于 some browsers (尤其不是 IE9 或更早版本),对于某些任务,您可以使用 web workers . Web Worker 是一个独立的 JavaScript 线程,与在后台运行的主 JavaScript 线程分开。这两个线程通过相互发布消息进行通信。
因此您可以启动网络 worker ,将工作交给它,然后让它向您发送消息以更新您的进度条。 This article提供网络 worker 的基础知识,如果你想走那条路的话。
就其值(value)而言,它看起来像这样:
主要文档和脚本:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Progress</title>
<style type="text/css">
body, html {
height: 100%;
}
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<div id="progress"><em>(Click to start)</em></div>
<script>
(function() {
var div = document.getElementById("progress");
var counter = new Worker("counter.js");
div.addEventListener("click", run);
counter.addEventListener("message", function(event) {
div.innerHTML = "Counter so far: " + event.data.counter;
});
function run() {
div.removeEventListener("click", run);
counter.postMessage({ max: 10000000 });
}
})();
</script>
</body>
</html>
counter.js
web-worker 脚本(它们总是单独的文件):
self.addEventListener("message", function(event) {
var max;
var counter;
max = event.data && event.data.max || 100000;
for (counter = 0; counter < max; ++counter) {
if (counter % 1000 === 0) {
self.postMessage({counter: counter});
}
}
self.postMessage({counter: counter});
});
关于javascript - for循环中的进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17552478/