Synchronous and asynchronous requests

This translation is incomplete. Please help translate this article from English

XMLHttpRequest підтримує обидва синхронний та асинхронний типи комунікації. Попри це, зазвичай, саме асинхронним запитам має надаватися перевага над синхронними з питань швидкодії.

Синхронні запити блокують виконання коду що призводить до  зупинки оновлення экрану ("freezing"), та відсутньої реакції на дії користувача.

Асинхронні запити

Якщо ви використовуєте асинхронний XMLHttpRequest, ви отримаєте сповіщення через функцію зворотного виклику коли дані будуть отримані. Це дозволяє бравзеру продовжити роботу в звичайному режимі поки ваш запит обробляється.

Приклад: відправка файлу до журналу консолі

Це найпростіший приклад використання асинхронного XMLHttpRequest.

var xhr = new XMLHttpRequest();"GET", "/bar/foo.txt", true);
xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
    } else {
xhr.onerror = function (e) {

Другий рядок передає true як третій параметер функції цим вказує що запит має бути опрацьований асинхронно.

Строка три створює функцію обробника події та назнає її до атрибуту onload запита. Цей обробник спостерігає за readyState запита для того, щоб виявити завершення передачі в рядку 4, і якщо так і є та статус HTTP 200 — виводить контент. Якщо сталась помилка — виводить повідомлення про помилку.

Строка 15 фактично ініціює запит. Зворотній виклик викликається кожного разу, коли змінюється статус запиту.

Приклад: створення стандартної функції для читання зовнішніх файлів

In some cases you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

function xhrSuccess() { 
    this.callback.apply(this, this.arguments); 

function xhrError() { 

function loadFile(url, callback /*, opt_arg1, opt_arg2, ... */) {
    var xhr = new XMLHttpRequest();
    xhr.callback = callback;
    xhr.arguments =, 2);
    xhr.onload = xhrSuccess;
    xhr.onerror = xhrError;"GET", url, true);


function showMessage(message) {
    console.log(message + this.responseText);

loadFile("message.txt", showMessage, "New message!\n\n");

The signature of the utility function loadFile declares (i) a target URL to read (via HTTP GET), (ii) a function to execute on successful completion of the XHR operation, and (iii) an arbitrary list of additional arguments that are "passed through" the XHR object to the success callback function.

Line 1 declares a function invoked when the XHR operation completes successfully.  It, in turn, invokes the callback function specified in the invocation of the loadFile function (in this case, the function showMessage) which has been assigned to a property of the XHR object (Line 7). The additional arguments (if any) supplied to the invocation of function loadFile are "applied" to the running of the callback function.

Line 5 declares a function invoked when the XHR operation fails to complete successfully.

Line 7 stores on the XHR object the success callback function given as the second argument to loadFile.

Line 12 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable xhr, passed to the success callback function xhrSuccess., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess.

Line 15 specifies true for its third parameter to indicate that the request should be handled asynchronously.

Line 16 actually initiates the request.

Example: using a timeout

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

function loadFile(url, timeout, callback) {
    var args =, 3);
    var xhr = new XMLHttpRequest();
    xhr.ontimeout = function () {
        console.error("The request for " + url + " timed out.");
    xhr.onload = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                callback.apply(xhr, args);
            } else {
    };"GET", url, true);
    xhr.timeout = timeout;

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.


function showMessage (message) {
    console.log(message + this.responseText);

loadFile("message.txt", 2000, showMessage, "New message!\n");

Here, we're specifying a timeout of 2000 ms.

Note: Support for timeout was added in Gecko 12.0.

Synchronous request

Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), Blink 39.0, and Edge 13, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.

Synchronous XHR often causes hangs on the web. But developers typically don't notice the problem because the hang only manifests during poor network conditions or slow server response. Synchronous XHR is now in deprecation state. Developers are recommended to move away from the API.

All new XHR features such as timeout or abort aren't allowed for synchronous XHR. Doing so would invoke InvalidAccessError

Example: HTTP synchronous request

This example demonstrates how to make a simple synchronous request.

var request = new XMLHttpRequest();'GET', '/bar/foo.txt', false);  // `false` makes the request synchronous

if (request.status === 200) {

Line 3 sends the request.  The null parameter indicates that no body content is needed for the GET request.

Line 5 checks the status code after the transaction is completed.  If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

Example: Synchronous HTTP request from a Worker

One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker.

example.html (the main page):

<!doctype html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example</title>
<script type="text/javascript">
  var worker = new Worker("myTask.js");  
  worker.onmessage = function(event) {  
    alert("Worker said: " +;


myFile.txt (the target of the synchronous XMLHttpRequest invocation):

Hello World!!

myTask.js (the Worker):

self.onmessage = function (event) {
  if ( === "Hello") {
    var xhr = new XMLHttpRequest();"GET", "myFile.txt", false);  // synchronous request
Note: The effect, because of the use of the Worker, is however asynchronous.

It could be useful in order to interact in background with the server or to preload some content. See Using web workers for examples and details.

Adapting Sync XHR usecases to the Beacon API

There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the window.onunload and window.onbeforeunload events. You should consider using the fetch API with keepalive flag. When fetch with keepalive isn't available, you can consider using the navigator.sendBeacon API can support these usecases typically while delivering a good UX.

The following example (from the sendBeacon docs) shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.

window.addEventListener('unload', logData, false);

function logData() {
    var client = new XMLHttpRequest();"POST", "/log", false); // third parameter indicates sync xhr. :(
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

The following example shows a theoretical analytics code pattern that submits data to a server using the by using the sendBeacon() method.

window.addEventListener('unload', logData, false);

function logData() {
    navigator.sendBeacon("/log", analyticsData);

See also