JavaScript Execution Order Problem
The following works correctly:
alert("start");
loadData(); // takes a while
alert("finished");
loadData() is a method that inserts large amounts of data into a table in the DOM and takes a few seconds.
This, however, does not work as expected:
document.getElementById("mydiv").style.display = "block";
开发者_开发百科loadData(); // takes a while
document.getElementById("mydiv").style.display = "none";
The data is loaded into the table without displaying mydiv until the loading is completed and then mydiv is quickly displayed and gone.
But this works like it's supposed to:
document.getElementById("mydiv").style.display = "block";
alert("start");
loadData(); // takes a while
alert("finish");
document.getElementById("mydiv").style.display = "none";
mydiv is displayed, the alert dialog is shown, the data is loaded into the table, and then mydiv disappears, as expected.
Anyone know why the second code section above does not work properly?
I dont know the exact reason, but i can think of is that LoadData is a heavy function so browser is busy evaluating that, so it holds the rendering. When u give alert in between it provides sufficient time to render div and then evaluate LoadData.
Work Around:
function LoadData()
{
//Show Div here
//window.setTimeout(newFunc,100);
}
function newFunc()
{
//Do data operations here
//Hide Div
}
Think of javascript as inserting some interpreted code into a larger program. The larger program looks a little like this:
void eventLoop () {
struct event event;
while(event = getEvent()){
runJavascript(event);
runBrowserCode();
if(viewHasChanged) {
redrawViewRegions();
}
}
}
This isn't really accurate at all, but it gives you a little bit of an idea. While javascript code is running, the browser is not doing anything else: including updating the view. it hasn't got up to that bit. The browser gui does not run in a seperate asynchronous thread, in parallel to the javascript as you seem to imagine. The browser has to wait for javascript to finish before it can do anything.
You can see the gui update when you use alerts, because, well- To display an alert you have to update the gui! so it's kind of a special case.
精彩评论