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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With