I am working on displaying a progress bar using JQuery during a long running function. My plan is to simply show the div containing the progress bar before calling the function, and then hiding the div after the function is finished. The following code example demonstrates what I am trying to accomplish.
$(document).ready(function() {
$(document).click(function() {
$("#progress").show();
slowFunction();
$("#progress").hide();
});
});
function slowFunction() {
for (var i = 0; i < 50000; ++i) {
var t = Math.sin(i) + Math.cos(i);
console.log(t);
}
}
Example on JSFiddle http://jsfiddle.net/MT25x/4/
The problem is that the div is not being displayed at all even though the function takes ~10 seconds on my machine to run.
If however I just try to show the div after the function it works fine, coming up in ~10 or so seconds after the click occurs. Can anybody help me shed some light on this issue?
Edit:
Further testing seems to show that if you remove the hide call all together the div isn’t even showing until after the function has finished running. This seems like very odd behavior.
This is a common problem with most browsers. When a cpu intensive function runs it locks the main executing thread and the browser doesn’t do a repaint until the function has finished executing, hence the div is getting hidden and shown really fast because both show and hide were queued. To circumvent this you can use the
setTimeout(...,0)trick, this queues the function for immediate execution. This is not guaranteed to work cross browser and i have only tested this on ie, chrome and firefox.Here’s a fiddle.