lets say you are processing a bunch of data and now that will take some time (in my case I’m accessing multiple resources via AJAX and after receiving them I parse them with RegExp [that parsing is what takes the critical amount of time]).
You also would like to assure 2 things:
- The browser does not feel frozen
- The user has some kind of indicator
I made the following example with jQuery(UI):
JS:
$(function() {
$("#progressbar").progressbar({
value: 0
});
$("#blub").click(function() {
i = 0;
while(i < 5000) {
$("#progressbar").progressbar({
value: (i / 5000 * 100)
});
i++;
}
});
});
HTML:
<div id="progressbar"></div>
<div id="blub">KLICK</div>
It seems like the browser is only redrawing its canvas when the while is completely done.
Also the CPU-Usage goes as high as it can.
Is there any way to force breaks or reduce the CPU-Load?
You should use
requestAnimationFrameinstead of awhileloop to render the result after every pass.Here’s the
requestAnimatonFramepolyfill that falls back tosetTimeouthttps://gist.github.com/1579671And here’s how you would replace your
whileloop which does not allow the screen to refresh or render until it is done computing.