在循环多个变量时使用setTimeout更新进度条 [英] Using setTimeout to update progress bar when looping over multiple variables

查看:230
本文介绍了在循环多个变量时使用setTimeout更新进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有3个要循环的数组,长度为x,y和z,并且对于每个循环,您想要更新进度条。例如:

  function run(){
x = 100;
y = 100;
z = 10;
count = 0;
for(i = 0; i< x; i ++){
//某些代码
for(j = 0; j< y; j ++){
//一些代码
for(k = 0; k< z; k ++){
//一些代码
$(#progressbar)。reportprogress(100 * ++ count /(x * y *) Z));
}
}
}
}

但是在此示例中,进度条在函数完成之前不会更新。因此,我相信我需要使用setTimeout在函数运行时更新进度条,虽然我不知道如何在嵌套for循环时这样做。



<我是否需要将每个循环分解为自己的函数,还是可以将它们作为循环嵌套用于循环?



我创建了一个jsfiddle页面以防万一喜欢运行当前功能: http://jsfiddle.net/jrenfree/6V4Xp/



谢谢!

解决方案

如果你想使用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);
}
}
}
}

< a href =http://jsfiddle.net/6V4Xp/12/ =nofollow>现场演示。


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

Live demo.

这篇关于在循环多个变量时使用setTimeout更新进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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