Reputation: 106
Here is my sample code. (The reason I need to send synchronous requests is that actually I need to send several requests and each requests depends on the previous request's response. And the reason I need to set callbacks is that I want to show some spinner, so users knows the status of the script.)
var xmlhttp =new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==2) {
document.getElementById("p2").style.color = "blue"; //statment 1
}
if (xmlhttp.readyState==4) {
document.getElementById("p2").style.color = "red"; //statment 2
}
}
xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
balblabla(); // a time-cost function
Then I have 2 questions. First, when will statement 1 and statement 2 actually get executed? Is it guaranteed to get executed before balblabla()?
Second, Even if statement 1 and statement 2 get executed, seems browser won't actually change the displayed color until blablabla() is finished. Is there a way to make color change got displayed before blablabla() finished? (assuming blablabla() takes a long time)
Thanks!
Upvotes: 0
Views: 234
Reputation: 114014
If the XHR is synchronous then the callbacks are executed before .send()
returns. In other words before blablabla()
.
Browser DOM updates are asynchronous. Or rather, the redraws are asynchronous (DOM update/reflow can at times be synchronous but it won't draw to screen, just update data structures).
So, even if you insist on not learning how to write asynchronous programs by using synchronous XMLHttpRequest you can't draw anything synchronously. You'd be better off writing everything asynchronous.
note: To be clear, redraw only happens when the javascript interpreter have nothing else to run. In other words, the browser window will only be updated after blablabla()
completes running.
If blablabla()
takes a long time to execute, you can break up the loop using setTimeout()
to make it asynchronous. Alternatively you can try using webworkers.
Upvotes: 1