2

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();
};
Andrej Mikulik
  • 569
  • 5
  • 14
  • 1
    possible duplicate of [Javascript progress bar not updating 'on the fly', but all-at-once once process finished?](http://stackoverflow.com/questions/5743428/javascript-progress-bar-not-updating-on-the-fly-but-all-at-once-once-process), also try http://jsfiddle.net/nNZCE/ – oleq Aug 05 '13 at 13:29
  • Thanks, I tried their solution, but for some unknown reason I could make it with newer jQuery... Your solution works for me. Thanks! – Andrej Mikulik Aug 05 '13 at 13:56

2 Answers2

1

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 );
Andrej Mikulik
  • 569
  • 5
  • 14
0

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);  
    }    
});
  • http://jsfiddle.net/mQqcK/ your solution is not working as expected... Something is updating, but not corresponding with console output. After finishing the script the progress-bar updates fast to 100%. – Andrej Mikulik Aug 05 '13 at 14:09
  • Solution from Oleg works. How can I close this question if the answer is only in comment? – Andrej Mikulik Aug 05 '13 at 14:10
  • Indeed @Andrej, I think its because the heavycomp delay is equal to the timeout. I've changed the fiddle and seems to be working. However the solution presented by oleq looks better. – Rogério Jesus Aug 06 '13 at 09:09