在每个循环中更新进度条 [英] Update progressbar in each loop

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

问题描述

我有一个进度条,可以在多次迭代中进行更新.

I have a progress bar that I update in a loop of many iterations.

https://jsfiddle.net/k29qy0do/32/ (在点击开始按钮之前打开控制台)

https://jsfiddle.net/k29qy0do/32/ (open the console before you click the start button)

var progressbar = {};

$(function () {

    progressbar = {

        /** initial progress */
        progress: 0,

        /** maximum width of progressbar */
        progress_max: 0,

        /** The inner element of the progressbar (filled box). */
        $progress_bar: $('#progressbar'),

        /** Set the progressbar */
        set: function (num) {
            if (this.progress_max && num) {
                this.progress = num / this.progress_max * 100;
                console.log('percent: ' + this.progress + '% - ' + num + '/' + this.progress_max);

                this.$progress_bar.width(String(this.progress) + '%');
            }
        },

        fn_wrap: function (num) {
            setTimeout(function() {
                this.set(num);
            }, 0);
        }

    };

});


$('#start_button').on('click', function () {

    var iterations = 1000000000;

    progressbar.progress_max = iterations;

    var loop = function () {

        for (var i = 1; i <= iterations; i++) {

            if (iterations % i === 100) {

                progressbar.set(i); //only updates the progressbar in the last iteration

                //progressbar.fn_wrap(i); //even worse, since no output to the console is produced

            }
        }
    }

    //setTimeout(loop, 0);
    loop();

});

控制台将按预期进行迭代更新. 但是,进度条没有更新.

The console is updated iteratively as expected. However, the progressbar is not updating.

问题在于,浏览器窗口似乎挂起",直到循环结束. 仅更新控制台,而不更新进度栏.

The problem is that the browser window seems to 'hang' until the loop finishes. Only the console is updated, not the progressbar.

我已尝试在以下几个地方添加setTimeout,如下所示. 但这只会使情况变得更糟,因为在执行循环时,我什至不让控制台输出进度.

I have tried to add the setTimeout, as suggested below, in several places. But that just makes things worse, because I then do not even get the console to output the progress while executing the loop.

推荐答案

好的,我在此问题的答案中找到了解决方案:

Okay, I found a solution in the answer to this question:

JavaScript:如何更新进度"for"循环中的条形

var i = 0;
(function loop() {
    i++;
    if (iterations % i === 100) {
        progressbar.set(i); //updates the progressbar, even in loop    
    }   
    if (i < iterations) {
        setTimeout(loop, 0);
    }
})();

我的解决方案: https://jsfiddle.net/ccvs4rer/3/

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

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