循环中的进度条 [英] progress bar in for loop

查看:219
本文介绍了循环中的进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(index = 0; index< 1000; index ++){在javascript中的for循环中需要一个进度条。

/ code>

  //将进度条值设为index / 1000 * 100 +'%'

}



我注意到我们可以把它放在一个 setInterval 函数中,但是运行for循环将花费更多的时间。



那么有没有什么办法可以运行for循环并生成进度条,而无需花费更多的时间呢?

解决方案


那么有没有什么办法可以运行for循环,并且无需花费更多的时间来生成进度条?

大多数情况下(请参阅下面为什么主要),你必须回到浏览器(例如,通过 setTimeout setInterval ),所以它可以更新页面显示,这确实会增加循环运行的时间。现在,通常如果使用 0 的超时,浏览器会在5到10毫秒之间回拨您。所以叫它10ms。在你的1000循环循环中,你可能会产生每100个周期(例如10次进度更新),这只会使总时间增加100ms左右。



FWIW,看起来像这样(假设它是一个你正在循环的数组):

$ $ $ $ $ $ $ $ $ $ c $ function $ loop(array,batchSize,callback) {
var index = 0;

doWork();

函数doWork(){
var limit = Math.min(array.length,index + batchSize);
while(index< limit){
//做一些数组[索引]
}
if(limit< max){
setTimeout(doWork, 0);
}
else {
callback(); //完成
}
}
}

/ b>

 循环(someArray,100,function(){
//完成
});为什么大多数不是:在


$ b


=http://caniuse.com/#feat=webworkers =nofollow>一些浏览器(不是特别是IE9或更早版本),对于某些任务,可以使用 web workers 。 Web Worker是一个独立的JavaScript线程,与主JavaScript线程分开,后者在后台运行。这两个线程通过相互发送消息进行通信。



所以你可以启动一个网络工作者,把它交给工作,并发布消息来更新你的进度酒吧。 这篇文章给出了网络工作者的基本知识,如果你想要走这条路。



它的价值看起来像这样:



主文档和脚本:

 <!doctype html> 
< html>
< head>
< meta charset =UTF-8>
< title>进度< / title>
< style type =text / css>
body,html {
height:100%;
}
body {
font-family:sans-serif;
}
< / style>
< / head>
< body>
< div id =progress>< em>(点击开始)< / 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 now:+ event.data .counter;
});

function run(){
div.removeEventListener(click,run);
counter.postMessage({max:10000000 });
}
})();
< / script>
< / body>
< / html>

counter.js web-worker脚本它们总是单独的文件):

$ p $ self.addEventListener(message,function(event){
var (counter = 0; counter var counter;
$ b max = event.data& event.data.max || 100000;
) ++ counter){
if(counter%1000 === 0){
self.postMessage({counter:counter});
}
}
self .postMessage({counter:counter});
});


I need a progress bar in a for loop in javascript

for(index=0; index < 1000; index++){

// set progress bar value to  index/1000 * 100 + '%'

}

I notice we can put it in a setInterval function, but it will cost more time to run the for loop.

So is there any way to run the for loop and generate the progress bar without cost more time?

解决方案

So is there any way to run the for loop and generate the progress bar without cost more time?

Mostly no (see below for why "mostly"), you have to yield back to the browser (e.g., via setTimeout or setInterval) so it can update the page display, and that will indeed increase the amount of time the loop runs. Now, typically if you use a timeout of 0, browsers will call you back in between 5 and 10 milliseconds. So call it 10ms. In your 1,000-cycle loop, you might yield every 100 cycles (e.g., 10 progress updates), which would only add 100ms or so to the total time.

FWIW, that looks like this (let's say it's an array you're looping through):

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
        }
    }
}

Use:

loop(someArray, 100, function() {
    // Done
});


Why "mostly" no: On some browsers (not, notably, IE9 or earlier), for some tasks, you could use web workers. A web worker is an isolated JavaScript thread, separate from the main JavaScript thread, which runs in the background. The two threads communicate by posting messages to each other.

So you could fire up a web worker, hand it the work, and have it post you messages to update your progress bar. This article gives the basics of web workers, if you want to go that route.

For what it's worth, it looks something like this:

Main document and script:

<!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 script (they're always separate files):

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});
});

这篇关于循环中的进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆