It seems most everyone does asynchronous requests with XMLHttpRequest but obviously the fact that there is the ability to do synchronous requests indicates there might be a valid reason to do so. So what might that valid reason be?
-
1That's a pretty good question! I don't think the answer will be very interesting, but great question nevertheless. Have you tried a synchronous call to see what will happen? – Tad Donaghe Jan 18 '10 at 18:38
-
3Synchronous calls block the browser which leads to a terrible user experience. Thus my question. I couldn't think of any good reason to use it. – Darrell Brogdon Jan 18 '10 at 18:40
-
2Semi-serious answer: maybe simply to fill the chapter that comes before the asynchronous requests in whatever JavaScript book you are reading. – Ben James Jan 18 '10 at 18:53
-
Personally, I'd like to use some syncronous ajax to wrap multiple calls to serverside functions without having to write a request for each call. – Paul Ishak Jan 18 '17 at 17:26
-
running code locally, especially for internal dev frameworks and tools. – Feb 13 '20 at 18:48
21 Answers
Synchronous XHRs are useful for saving user data. If you handle the beforeunload
event you can upload data to the server as the user closes the page.
If this were done using the async option, then the page could close before the request completes. Doing this synchronously ensures the request completes or fails in an expected way.

- 69,552
- 46
- 163
- 208

- 1,540
- 17
- 21
-
5Edited: I realize you're just dumping txt from a lazy HN user, but a little time in phrasing it nicely is appreciated here on SO. – Frank Krueger Aug 04 '11 at 16:41
-
-
-
1@DouglasHeld A website called Hacker News at news.ycombinator.com – Sami Samhuri Dec 23 '15 at 17:12
-
1The support for synchronous XHR in page dismissals is being phased out, Chrome already doesn't support it https://developers.google.com/web/updates/2019/12/chrome-80-deps-rems – pepkin88 Nov 13 '21 at 14:34
I think they might become more popular as HTML 5 standards progress. If a web application is given access to web workers, I could foresee developers using a dedicated web worker to make synchronous requests for, as Jonathan said, to ensure one request happens before another. With the current situation of one thread, it is a less than ideal design as it blocks until the request is complete.

- 6,612
- 3
- 43
- 80

- 15,340
- 19
- 71
- 102
-
17
-
I think the distilled point. In UI Thread, Create a thread or a async task of sorts. If in thread already, use synchronized under most cases. Threads are a lot more "block friendly" – HaMMeReD Aug 04 '11 at 06:18
-
This is an old answer, but this comment applies to even back then, even before HTML5, browsers provided for 2 threads for making requests. I wrote a connection pool script to utilize both, because even with async request, with one connection, you could tie the browser up. Making use of both allows for more data to be pushed/pulled through the line; but iirc, I think the sync requests still tied up the browser. – vol7ron Mar 06 '13 at 22:55
-
Firefox (and probable all non-IE browsers) does not support async XHR timeOut. HTML5 WebWorkers do support timeouts. So, you may want to wrap sync XHR request to WebWorker with timeout to implement async-like XHR with timeout behaviour. – Dmitry Kaigorodov Aug 22 '13 at 22:01
-
3-1. This isn't much of an answer and the whole discussion about threads is only confusing the matter. The answer below by Sami is actually much better. – Stijn de Witt Jul 24 '15 at 12:24
-
It depends on what you are making and what you are making it for. How about for devs running tools off of localhost? Not everything created using web tools is run on the web. – Feb 13 '20 at 18:46
Update:
The below hinted at - but was unsuccessful in delivering - that with the advent of better asynchronous request handling, there really is no reason to use synchronous requests, unless intending to purposely block the users from doing anything until a request is complete - sounds malicious :)
Although, this may sound bad, there may be times where it's important that a request (or series of requests) occur before a user leaves a page, or before an action is performed - blocking other code execution (e.g., preventing back button) could possibly reduce errors/maintenance for a poorly designed system; that said, I've never seen it in the wild and stress that it should be avoided.
Libraries, like promise, feign synchronicity by chaining processes via callbacks. This suits the majority of development needs where the desire is to have ordered, non-blocking events that enable the browsers to retain responsiveness for the user (good UX).
As stated in the Mozilla docs there are cases where you have to use synchronous requests; however, also listed is a workaround that uses beacon (not available in IE/Safari) for such cases. While this is experimental, if it ever reaches standards-acceptance, it could possibly put a nail in the synchronous-request coffin.
You'd want to perform synchronous calls in any sort of transaction-like processing, or wherever any order of operation is necessary.
For instance, let's say you want to customize an event to log you out after playing a song. If the logout operation occurs first, then the song will never be played. This requires synchronizing the requests.
Another reason would be when working with a WebService, especially when performing math on the server.
Example: Server has a variable with value of 1.
Step (1) Perform Update: add 1 to variable Step (2) Perform Update: set variable to the power of 3 End Value: variable equals 8
If Step (2) occurs first, then the end value is 2, not 8; thus order of operation matters and synchronization is needed.
There are very few times that a synchronous call may be justified in a common real world example. Perhaps when clicking login and then clicking a portion of the site that requires a user to be logged in.
As others have said, it will tie up your browser, so stay away from it where you can.
Instead of synchronous calls, though, often users want to stop an event that is currently loading and then perform some other operation. In a way this is synchronization, since the first event is quit before the second begins. To do this, use the abort() method on the xml connection object.
-
1
-
We use synchronous calls on our intranet's "contacts" and "favorites" pages, where we need to ensure a user's data is loaded before we can update the DOM. – Zack The Human Jul 23 '10 at 19:53
-
3@Zack: that's a good example, however you could probably do the same with asynchronous calls depending on the event that is calling it. – vol7ron Jul 23 '10 at 23:33
-
3+1 There is a valid case that logical race conditions can result from asynchronous server requests... However, the solution doesn't have to be synchronicity. Unless your requests are being handled from a Web Worker, it would be better to write a transport layer that would number the requests and then ensure operations are handled in order of request ids. – Roy Tinker Aug 04 '11 at 17:29
-
@Roy +1, as you have just described how TCP/IP works. The second part of a TCP packet is the `sequence number`, which is a 32bit number used for ordering packets, since messages aren't always received in the order they're sent. – vol7ron Aug 04 '11 at 22:09
-
3-1 Transaction processing is a perfect example where you must use guarantee's that stuff fails or succeeds - just because the command is synchronous, doesn't mean that the first request succeeded... you have rely on the response telling you such. In this example you would do the second request *only* from within the result-handler of the first request - in which case they both might as well be async. – Mathew Oct 17 '12 at 21:20
-
2@Mathew: that is only true if your transaction-like process is dependent on the result of the action before it. If you have a button that creates a new object (retrieved from the server) in your page; if it was asynchronous the user could potentially click multiple times and return many objects. A synchronous call would prevent that and only allow another new object to be created after the first has finished, regardless if it errored out, or not. Please pay attention to wording, I made it ***transaction-like*** and not ***transaction*** on purpose. – vol7ron Oct 17 '12 at 22:00
-
1@Mathew: additionally, the question was *is there a reason to use it...* not how do implement it; which any OLTP could be complicated, given that transactions have different conditions/requirements – vol7ron Oct 17 '12 at 22:06
-
@Mathew You are right. This answer is wrong. Sync vs async is about the called function completing before or after the request has returned. It's not about order. All order issues can be easily handled with async as well. – Stijn de Witt Jul 24 '15 at 11:50
-
@StijndeWitt way to bring up the past ;) First, you've just said two conflicting statements.. `It's not about order`, but right before that you said it's about `completing before or after the request`. *Before* and *after* **IS** order. Second, what you've described for async requests is referred to as daisy chaining, but that method can also be applied to synchronous requests, so I'm not sure what point you're making. With regards to Matthew's statement, if the success of the request is important, then you could easily test for success and use a loop, or recursion, until it succeeds. – vol7ron Jul 24 '15 at 14:45
-
@vol7ron Yeah I like excavating. And no it is not about order in the sense your answer suggests. Async just means not waiting for something to complete. It's not about the order between multiple commands. You use async when something is blocking. You use synch when it is not blocking, or, when you need the result before you return. The OP's question is specifically about synchronous XMLHTTPRequest. Using that because that way you can get the requests to fire in the right order is wrong and will lead to slow apps. But hey if you think it's a good idea go right ahead. – Stijn de Witt Jan 10 '16 at 02:33
-
@StijndeWitt there are certainly alternatives from this 5.5 year old answer; but the advice not to use synchronous Ajax requests have already been stated at the bottom of the answer, which coincide with your comment. It is rare to use them, I think the best example might be to use it to logout of a website during the *onunload* event. With regards to blocking, that's not necessarily true. A developer can place their synchronous request inside a Worker and it would not be blocking (https://developer.mozilla.org/en-US/docs/Web/API/Worker). – vol7ron Jan 10 '16 at 08:48
-
Also, no problem with "excavating"; this question probably still applies so the answer probably needs to be refined. If I have time, I'll look at updating it, or you can make an edit. The only bad time to bring up the dead is when a question no longer applies, most likely due to outdated/deprecated technology. – vol7ron Jan 10 '16 at 08:49
-
"there really is no reason to use synchronous requests". Think internal tooling, frameworks for local developer testing/debugging. Not everything that is made with web tools is ran on the web: localhost – Feb 13 '20 at 18:53
I'd say that if you consider blocking the user's browser while the request completes acceptable, then sure use a synchronous request.
If serialization of requests is your aim, then this can be accomplished using async requests, by having the onComplete callback of your previous request fire the next in line.

- 28,925
- 4
- 72
- 77
-
1Hmm, I'd add a sliding window to that, otherwise you'll basically lose the round-trip time for each request – Stephan Eggermont Jan 18 '10 at 18:49
There are many real world cases where blocking the UI is exactly the desired behaviour.
Take an app with multiple fields and some fields must be validated by a xmlhttp call to a remote server providing as input this field's value and other fields values.
In synchronous mode, the logic is simple, the blocking experienced by the user is very short and there is no problem.
In async mode, the user may change the values of any other fields while the initial one is being validated. These changes will trigger other xmlhttp calls with values from the initial field not yet validated. What happens if the initial validation failed ? Pure mess. If sync mode becomes deprecated and prohibited, the application logic becomes a nightmare to handle. Basically the application has to be re-written to manage locks (eg. disable other items during validation processes). Code complexity increases tremendously. Failing to do so may lead to logic failure and ultimately data corruption.
Basically the question is: what is more important, non-blocked UI experience or risk of data corruption ? The answer should remain with the application developer, not the W3C.

- 141
- 1
- 8
-
3I think you're conflating the idea of blocking user interaction with blocking the browser thread. There are a billion, simple, ways to prevent the user from continuing to interact with any given entity (form field, etc) during an async call that would not require blocking the browser thread. When the thread is blocking, there cannot be _any_ logical processing, whatsoever, and that's just a bad situation to be in; it creates far more problems/potential problems, that are virtually unsolvable, than it solves. – Luke Chavers Mar 21 '17 at 04:37
I can see a use for synchronous XHR requests to be used when a resource in a variable location must be loaded before other static resources in the page that depend on the first resource to fully function. In point of fact, I'm implementing such an XHR request in a little sub-project of my own whereas JavaScript resources reside in variable locations on the server depending on a set of specific parameters. Subsequent JavaScript resources rely on those variable resources and such files MUST be guaranteed to load before the other reliant files are loaded, thus making the application whole.
That idea foundation really kind of expands on vol7ron's answer. Transaction-based procedures are really the only time where synchronous requests should be made. In most other cases, asynchronous calls are the better alternative in which, after the call, the DOM is updated as necessary. In many cases, such as user-based systems, you could have certain features locked to "unauthorized users" until they have, per se, logged in. The those features, after the asynchronous call, are unlocked via a DOM update procedure.
I'd have to finally say that I agree with most individuals' points on the matter: wherever possible, synchronous XHR requests should be avoided as, with the way it works, the browser locks up with synchronous calls. When implementing synchronous requests, they should be done in a manner where the browser would normally be locked, anyway, say in the HEAD section before page loading actually occurs.

- 63
- 1
- 5
-
1The fact that an action relies upon the result of another action is no reason to perform that other action synchronously. Only if the result of some action must be processed *before the calling function terminates* do you need a synchronous call. – Stijn de Witt Jul 24 '15 at 12:33
jQuery uses synchronous AJAX internally under some circumstances. When inserting HTML that contains scripts, the browser will not execute them. The scripts need to be executed manually. These scripts may attach click handlers. Assume a user clicks on an element before the handler is attached and the page would not function as intended. Therefore to prevent race conditions, synchronous AJAX would be used to fetch those scripts. Because synchronous AJAX effectively blocks everything else, it can be sure that scripts and events execute in the right order.

- 1,339
- 13
- 24
As of 2015 desktop javascript apps are becoming more popular. Usually in those apps when loading local files (and loading them using XHR is a perfectly valid option), the load speed is so fast that there is little point overcomplicating the code with async. Of course there might be cases where async is the way to go (requesting content from the internet, loading really big files or a huge number of files in a single batch), but otherwise sync works just fine (and is much easier to use).

- 5,427
- 3
- 37
- 64
-
This is actually the situation I find myself in and it's 2020. I have a desktop app that displays its UI via HTTP so you can access it from a browser running on the local machine or even across the network. In these scenarios the network is fast and reliable so doing synchronous XHR requests is a great way to keep the code simple. Most people don't realise that async XHR requests are like using threads and that can get really complicated with many opportunities for bugs. – Eric Mutta May 11 '20 at 02:34
Reason:
Let's say you have an ajax application which needs to do half a dozen http gets to load various data from the server before the user can do any interaction.
Obviously you want this triggered from onload.
Synchronous calls work very well for this without any added complexity to the code. It is simple and straightforward.
Drawback:
The only drawback is that your browser locks up until all data is loaded or a timeout happens. As for the ajax application in question, this isn't much of a problem because the application is of no use until all the initial data is loaded anyway.
Alternative?
However many browsers lock up all windows/tabs when while the javascript is busy in any one of them, which is a stupid browser design problem - but as a result blocking on possibly slow network gets is not polite if it keeps users from using other tabs while waiting for ajax page to load.
However, it looks like synchronous gets have been removed or restricted from recent browsers anyway. I'm not sure if that's because somebody decided they were just always bad, or if browser writers were confused by the WC Working Draft on the topic.
http://www.w3.org/TR/2012/WD-XMLHttpRequest-20120117/#the-open-method does make it look like (see section 4.7.3) you are not allowed to set a timeout when using blocking mode. Seems counter intuitive to me: Whenever one does blocking IO it's polite to set a reasonable timeout, so why allow blocking io but not with a user specified timeout?
My opinion is that blocking IO has a vital role in some situations but must be implemented correctly. While it is not acceptable for one browser tab or window to lock up all other tabs or windows, that's a browser design flaw. Shame where shame is due. But it is perfectly acceptable in some cases for an individual tab or window to be non-responsive for a couple of seconds (i.e. using blocking IO/HTTP GET) in some situations -- for example, on page load, perhaps a lot of data needs to be before anything can be done anyway. Sometimes properly implemented blocking code is the cleanest way to do it.
Of course equivalent function in this case can be obtained using asynchronous http gets, but what sort of goofy routine is required?
I guess I would try something along these lines:
On document load, do the following: 1: Set up 6 global "Done" flag variables, initialized to 0. 2: Execute all 6 background gets (Assuming the order didn't matter)
Then, the completion callbacks for each of the 6 http get's would set their respective "Done" flags. Also, each callback would check all the other done flags to see if all 6 HTTP gets had completed. The last callback to complete, upon seeing that all others had completed, would then call the REAL init function which would then set everything up, now that the data was all fetched.
If the order of the fetching mattered -- or if the webserver was unable to accept multiple requests at same time -- then you would need something like this:
In onload(), the first http get would be launched. In it's callback, the second one would be launched. In it's callback, the third -- and so on and so forth, with each callback launching the next HTTP GET. When the last one returned, then it would call the real init() routine.

- 1,455
- 15
- 16
What happens if you make a synchronous call in production code?
The sky falls down.
No seriously, the user does not like a locked up browser.

- 3,794
- 2
- 17
- 15
-
2The question is "why do it with XMLHTTPREQUEST" not "why do or not do sync calls" – Itay Moav -Malimovka Jan 18 '10 at 22:43
-
1
-
1He asks for use cases of sync calls... Not for the downsides of them (we all know these by now...) – Stijn de Witt Jul 24 '15 at 11:51
-
what user? are all users the same? how about engineers testing locally? ...so accessing files of the file system with very little lag???? – Feb 13 '20 at 18:44
I use it to validate a username, during the check that the username does not exist already.
I know it would be better to do that asynchronously, but then I should use a different code for this particular validation rule. I explain better. My validation setup uses some validation functions, which return true or false, depending if the data is valid.
Since the function has to return, I cannot use asynchronous techniques, so I just make that synchronous and hope that the server will answer promptly enough not to be too noticeable. If I used an AJAX callback, then I would have to handle the rest of the execution differently from the other validation methods.

- 20,253
- 23
- 114
- 183
-
One trick in such a scenario is to let the validation function just check a flag (which starts as `false`) and just set it to true or false when the server responds. onchange of the field you reset the flag and call the server again. – Stijn de Witt Dec 19 '18 at 21:52
Sometimes you have an action that depends in others. For example, action B can only be started if A is finished. The synchronous approach is usually used to avoid race conditions. Sometimes using a synchronous call is a simpler implementation then creating complex logic to check every state of your asynchronous calls that depend on each other.
The problem with this approach is that you "block" the user's browser until the action is finished (until the request returns, finishes, loads, etc). So be careful when using it.

- 10,924
- 1
- 30
- 38
-
The question is "why do it with XMLHTTPREQUEST" not "why do sync calls" – Itay Moav -Malimovka Jan 18 '10 at 22:43
-
The author himself says "**Synchronous** calls block the browser which leads to a terrible user experience." in a comment, so everyone in this thread applied for the "synchronous calls" approach. Why did you take this literal understanding of the question if you can't really say for sure what the author meant? – GmonC Jan 18 '10 at 23:19
I use synchronous calls when developing code- whatever you did while the request was commuting to and from the server can obscure the cause of an error.
When it's working, I make it asynchronous, but I try to include an abort timer and failure callbacks, cause you never know...

- 102,654
- 32
- 106
- 127
XMLHttpRequest
is traditionally used for asynchronous requests. Sometimes (for debugging, or specific business logic) you would like to change all/several of the async calls in one page to sync.
You would like to do it without changing everything in your JS code. The async/sync flag gives you that ability, and if designed correctly, you need only change one line in your code/change the value of one var
during execution time.

- 42,981
- 12
- 84
- 132

- 52,579
- 61
- 190
- 278
SYNC vs ASYNC: What is the difference?
Basically it boils down to this:
console.info('Hello, World!');
doSomething(function handleResult(result) {
console.info('Got result!');
});
console.info('Goodbye cruel world!');
When doSomething
is synchronous this would print:
Hello, World!
Got result!
Goodbye cruel world!
In contrast, if doSomething
is asynchronous, this would print:
Hello, World!
Goodbye cruel world!
Got result!
Because the function doSomething
is doing it's work asynchronously, it returns before it's work is done. So we only get the result after printing Goodbye cruel world!
If we are depending on the result of an asynch call, we need to place the depending code in the callback:
console.info('Hello, World!');
doSomething(function handleResult(result) {
console.info('Got result!');
if (result === 'good') {
console.info('I feel great!');
}
else {
console.info('Goodbye cruel world!');
}
});
As such, just the fact that 2 or three things need to happen in order is no reason to do them synchronously (though sync code is easier for most people to work with).
WHY USE SYNCHRONOUS XMLHTTPREQUEST?
There are some situations where you need the result before the called function completes. Consider this scenario:
function lives(name) {
return (name !== 'Elvis');
}
console.info('Elvis ' + (lives('Elvis') ? 'lives!' : 'has left the building...');
Suppose we have no control over the calling code (the console.info
line) and need to change function lives
to ask the server... There is no way we can do an async request to the server from within lives
and still have our response before lives
completes. So we wouldn't know whether to return true
or false
. The only way to get the result before the function completes is by doing a synchronous request.
As Sami Samhuri
mentions in his answer, a very real scenario where you may need an answer to your server request before your function terminates is the onbeforeunload
event, as it's the last function from your app that will ever run before the window being closed.
I DON'T NEED SYNCH CALLS, BUT I USE THEM ANYWAY AS THEY ARE EASIER
Please don't. Synchronous calls lock up your browser and make the app feel unresponsive. But you are right. Async code is harder. There is, however a way to make dealing with it much easier. Not as easy as sync code, but it's getting close: Promises.
Here is an example: Two asynch calls should both complete succesfully before a third segment of code may run:
var carRented = rentCar().then(function(car){
gasStation.refuel(car);
});
var hotelBooked = bookHotel().then(function(reservation) {
reservation.confirm();
});
Promise.all([carRented, hotelBooked]).then(function(){
// At this point our car is rented and our hotel booked.
goOnHoliday();
});
Here is how you would implement bookHotel
:
function bookHotel() {
return new Promise(function(resolve, reject){
if (roomsAvailable()) {
var reservation = reserveRoom();
resolve(reservation);
}
else {
reject(new Error('Could not book a reservation. No rooms available.'));
}
});
}
See also: Write Better JavaScript with Promises.

- 40,192
- 13
- 79
- 80
-
1"Please don't. Synchronous calls lock up your browser and make the app feel unresponsive" This is not always an issue. Imagine you are testing localhost, and you are a dev. – Feb 13 '20 at 19:05
Firefox (and probable all non-IE browsers) does not support async XHR timeOut.
HTML5 WebWorkers do support timeouts. So, you may want to wrap sync XHR request to WebWorker with timeout to implement async-like XHR with timeout behaviour.

- 1
- 1

- 1,512
- 18
- 27
I just had a situation where asynchronous requests for a list of urls called in succession using forEach (and a for loop) would cause the remaining requests to be cancelled. I switched to synchronous and they work as intended.

- 362
- 1
- 11
Synchronous XHR can be very useful for (non-production) internal tool and/or framework development. Imagine, for example, you wanted to load a code library synchronously on first access, like this:
get draw()
{
if (!_draw)
{
let file;
switch(config.option)
{
case 'svg':
file = 'svgdraw.js';
break;
case 'canvas':
file = 'canvasdraw.js';
break;
default:
file = 'webgldraw.js';
}
var request = new XMLHttpRequest();
request.open('GET', file, false);
request.send(null);
_draw = eval(request.responseText);
}
return _draw;
}
Before you get yourself in a tizzy and blindly regurgitate the evil's of eval, keep in mind that this is only for local testing. For production builds, _draw would already be set.
So, your code might look like this:
foo.drawLib.draw.something(); //loaded on demand
This is just one example of something that would be impossible to do without sync XHR. You could load this library up front, yes, or do a promise/callback, but you could not load the lib synchronously without sync XHR. Think about how much this type of thing could clean up your code...
The limits to what you can do with this for tooling and frameworks (running locally) is only limited by your imagination. Though, it appears imagination is a bit limited in the JavaScript world.
Using synchronous HTTP requests is a common practice in the mobile advertisement business.
Companies (aka "Publishers") that build applications often run ads to generate revenue. For this they install advertising SDKs into their app. Many exist (MoPub, Ogury, TapJob, AppNext, Google Ads AdMob).
These SDKs will serve ads in a webview.
When serving an ad to a user, it has to be a smoothe experience, especially when playing a video. There should be no buffering or loading at any moment.
To solve this precaching
is used. Where the media (picture / videos / etc) are loaded synchronously in background of the webview.
Why not do it asynchronously?
- This is part of a globally accepted standard
- The SDK listens for the
onload
event to know when the ad is "ready" to be served to the user
With the deprecation of synchronous XMLHttpRequests, ad business will most likely be forced to change the standard in the future unless another way can be determined.

- 16,349
- 8
- 82
- 131
Well here's one good reason. I wanted to do an http request then, depending on the result, call click() on an input type=file. This is not possible with asynchronous xhr or fetch. The callback loses the context "user action", so the call click() is ignored. Synchronous xhr saved my bacon.
onclick(event){
//here I can, but I don't want to.
//document.getElementById("myFileInput").click();
fetch("Validate.aspx", { method : "POST", body: formData, credentials: "include" })
.then((response)=>response.json())
.then(function (validResult) {
if (validResult.success) {
//here, I can't.
document.getElementById("myFileInput").click();
}
});
}

- 27,056
- 15
- 80
- 110