Andrej Mikulik
Andrej Mikulik

Reputation: 569

css progress-bar during long javascript computation

Using javascript with jquery and bootstrap, I would like to have nice progress bar during heavy javascript computation. I know exactly the progress state of computation, but CSS is not updating during the computation.

WebWorker is not a solution as I need to work with a model in main thread which I am not able to copy/clone easily to the worker.

Example: Progressbar is updated at the end. I want it to update during the process.

http://jsfiddle.net/K48B2/

html code:

<div class="progress">
    <div id="loading" class="bar progress-bar progress-bar-info" style="width: 0%"></div>
</div>

javascript code:

for (var i = 0; i <= 10; i++) {
    $('#loading').css('width', i * 10 + '%');
    heavycomputation();
};

Upvotes: 2

Views: 1532

Answers (2)

Andrej Mikulik
Andrej Mikulik

Reputation: 569

Oleq presented this solution, which works... jsfiddle.net/nNZCE

function heavycomp(millis, progress) {
    var date = new Date();
    var curDate = null;
    do {
        curDate = new Date();
    }
    while (curDate - date < millis);

    if ( progress > 10 )
        return;

    setTimeout( function() {
        console.log( progress );
        $('#loading').css('width', progress * 10 + '%');
        heavycomp( 200, ++progress );
    }, 200 );
}

heavycomp( 200, 0 );

Upvotes: 1

Rog&#233;rio Jesus
Rog&#233;rio Jesus

Reputation: 41

Is this closer to what you are looking for?

function heavycomp(millis) {
    var date = new Date();
    var curDate = null;
    do {
        curDate = new Date();
    }
    while (curDate - date < millis);
}

$(function() {
    for (var i = 0; i <= 100; i++) {
        setTimeout(function (i) {
           return function() {
                $('#loading').css('width', i + '%');
                $('#value').html(i + '%');
                console.log(i + '%');
                heavycomp(200);               
           }
        }(i),i * 200);  
    }    
});

Upvotes: 0

Related Questions