Reputation: 2121
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:
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?
Upvotes: 2
Views: 909
Reputation: 3842
You should use requestAnimationFrame
instead of a while
loop to render the result after every pass.
Here's the requestAnimatonFrame
polyfill that falls back to setTimeout
https://gist.github.com/1579671
And here's how you would replace your while
loop which does not allow the screen to refresh or render until it is done computing.
var i = 0;
animate();
function animate() {
requestAnimationFrame(animate);
$("#progressbar").progressbar({
value: (i / 5000 * 100)
});
i++;
}
Upvotes: 4