Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing issue with setTimeout

The code below demonstrates the issue I am having.

When the the js executes, the progress bar fills, as expected rapidly until the max has been reached.

However, the span#pbarval container is updated very slowly and completes LONG after the progress bar has finished.

$(document).ready(function () {
    var max= 20000,
        cur=0;
    function updatePBar(){
        cur++;
        jQuery("#pbar").val(cur);
        jQuery("#pbarval").html("" + Math.ceil(cur*100/max) + "%");
        if (cur<=max){
            setTimeout(updatePBar, 10);
        }
    }
    updatePBar();
});

You can see the code executing here: http://jsfiddle.net/EricBrian/fhtp6rpf/

Can somebody explain why this is? How to make it keep up with the progress bar?

Also, I noticed that if I switch tabs, the setTimeout seems to pause. The percentage does not update until I switch back to the tab it is running in.

Thanks! -e

like image 255
EC In Va Avatar asked Dec 14 '22 13:12

EC In Va


1 Answers

You're using cur for the value of the progress bar, so the progress bar is full when cur === 100, but you're displaying cur*100/max as the percentage which doesn't reach 100% until cur == 20000.

You should use the same formula cur*100/max for both, and since you want the quick speed you should also divide your max by 100:

http://jsfiddle.net/Paulpro/fhtp6rpf/2/

$(document).ready(function () {
    var max= 200,
        cur=0;
    function updatePBar(){
        cur++;
        jQuery("#pbar").val(cur*100/max);
        jQuery("#pbarval").html("" + Math.ceil(cur*100/max) + "%");
        if (cur<max){
            setTimeout(updatePBar, 10);
        }
    }
    updatePBar();
});

I also changed the test cur<=max to cur<max since you probably do not mean to increment cur an extra time when it is already at max.

like image 198
Paul Avatar answered Jan 03 '23 10:01

Paul