更新时间:2023-01-13 09:41:58
如果你想使用setTimeout你可以捕获x ,y,z和计数变量到闭包中:
function run(){
var x = 100,
y = 100,
z = 10,
count = 0;
for(var i = 0; i< x; i ++){
for(var j = 0; j< y; j ++){
for(var k = 0; k< z ; k ++){
(function(x,y,z,count){
window.setTimeout(function(){
$('#progressbar')。reportprogress((100 * count) )/(x * y * z));
},100);
})(x,y,z,++ count);
}
}
}
}
现场演示。
Suppose you have 3 arrays you want to loop over, with lengths x, y, and z, and for each loop, you want to update a progress bar. For example:
function run() {
x = 100;
y = 100;
z = 10;
count = 0;
for (i=0; i<x; i++) {
//some code
for (j=0; j<y; j++) {
// some code
for (k=0; k<z; k++) {
//some code
$("#progressbar").reportprogress(100*++count/(x*y*z));
}
}
}
}
However, in this example, the progress bar doesn't update until the function completes. Therefore, I believe I need to use setTimeout to make the progress bar update while the function runs, although I'm not sure how to do that when you have nested for loops.
Do I need to break each loop up into its own function, or can I leave them as nested for loops?
I created a jsfiddle page in case you'd like to run the current function: http://jsfiddle.net/jrenfree/6V4Xp/
Thanks!
If you want to use setTimeout you could capture the x, y, z and count variables into a closure:
function run() {
var x = 100,
y = 100,
z = 10,
count = 0;
for (var i=0; i<x; i++) {
for (var j=0; j<y; j++) {
for (var k=0; k<z; k++) {
(function(x, y, z, count) {
window.setTimeout(function() {
$('#progressbar').reportprogress((100*count)/(x*y*z));
}, 100);
})(x, y, z, ++count);
}
}
}
}