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

2 Answers 2

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 );
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

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%.
Solution from Oleg works. How can I close this question if the answer is only in comment?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.