Timing with setTimeout

The code below demonstrates the problem I am facing.

When js is executed, the progress bar fills up, as expected, quickly until the maximum value is reached.

However, the span # pbarval container updates very slowly and exits LONG after the completion of the execution line.

$(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 executable code here: http://jsfiddle.net/EricBrian/fhtp6rpf/

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

Also, I noticed that if I switch tabs, setTimeout seems to pause. The percentage is not updated until I return to the tab in which it is running.

Thank! -e

+4
source share
6

cur , cur === 100, cur*100/max , 100% , cur == 20000.

cur*100/max , , 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();
});

cur<=max cur<max, , , cur , max.

+4

- 100, javascript max - 2000.

, , .

:

Math.ceil(cur*100/max)
+2

, .

Math.ceil(cur*100/max) 

cur

, .

+2

. setTimeout , . , , , , . , .

+2

cur

$(document).ready(function () {
     var max= 20000,
         cur=0;

     function updatePBar(){
         cur++;
         var value = Math.ceil((cur/max) * 100);
         jQuery("#pbar").val(value);
         console.log(cur)
         jQuery("#pbarval").html("" + value + "%");
         if (cur<=max){
             setTimeout(function(){updatePBar();}, 10);
         }
     }
     updatePBar();
});
+1

.

:

var max = 20000,
    cur = 0;
(function updatePBar() {
  pbarval.innerHTML = (pbar.value = Math.ceil(++cur * 100 / max)) + "%";
  if (cur < max) setTimeout(updatePBar, 10);
})();
<progress id="pbar" value="0" max="100"></progress>
<span id="pbarval"></span>
Hide result
+1

All Articles