I have a function which is called on a click of a button and it takes a long time to create and append to the DOM some elements so I would like to display a PopupPanel with a "loading" icon while the function finished what it has to do. Please note that my function does not make a call to the server, it only creates some elements in the UI which take a long time to compute, so I don't have an onSuccess() event or a callback function to work with.
So I have my PopupPanel:
pp = new PopupPanel();
pp.setTitle("loading....");
pp.setGlassEnabled(true);
Then on the click handler I have the following code:
public void onClick(ClickEvent event) {
pp.show();
functionWhichTakesaLongTimeToExecute();
pp.hide();
}
Since JavaScript is single-threaded I was expecting that the PopUp will appear, then functionWhichTakesaLongTimeToExecute() executes and then the PopUp to be hidden but what happens is that functionWhichTakesaLongTimeToExecute() executes first, taking a long time to append the elements to the DOM, and only after it has finished doing its job is the PopUp shown and then hidden. It is as if like the code was:
functionWhichTakesaLongTimeToExecute();
pp.show();
pp.hide();
What bothers me even more is that if I add a Window.alert("test") after pp.show() this will break the flow until the OK button in the alert is pressd and this causes the PopUp to appear before the alert and before functionWhichTakesaLongTimeToExecute() is called. So the following code works as expected:
pp.show();
Window.alert("test");
functionWhichTakesaLongTimeToExecute();
pp.hide();
Can somebody please explain to me why the PopUp is not displayed before the functionWhichTakesaLongTimeToExecute() is called but instead it "waits" for functionWhichTakesaLongTimeToExecute() to execute and only after that it gets to be displayed and why adding a Window.alert("test") causes it to be displayed properly?
PS: I have tested the code in both IE8 and Chrome and the behavior is the same.