What could be the reason for XMLHttpRequest to freeze with no error until it reaches the default browser timeout limit

As a front end developer, I have some gaps in my understanding of how networks operate. When a Javascript XMLHttpRequest times out, the ontimeout handler gets triggered. In case the XMLHttpRequest.timeout property is not set (which is supported in modern browsers), the request will wait for the default time limit set by the browser (e.g., 300 seconds / 5 minutes in Chrome).

If I make a request to a non-existent address or a server that is down, I should expect an error response, correct? Now, what specific network or server condition would cause the request to hang until it times out instead of quickly returning an error response?

Answer №1

When an XMLHttpRequest timeout ProgressEvent occurs, it means:

The request has taken longer than the specified timeout to complete.

Factors that can cause a request to hang include slow servers, large response payloads, network connection issues, and slow client connections.

  • Slow server
  • Huge response payload
  • Loss of network connection
  • Slow client network connection

These are just a few examples.

If I try to send a request to a non-existent address or a server that is down, will I receive an error response?

A non-existent address may return a DNS server error, while a downed server won't respond at all. The outcome depends on your timeout settings and the redundancy measures in place for the unreachable server.

Answer №2

Introduction

Typically, on the server side, there is a thread pool or event queue to handle incoming requests (referred to as the IO thread pool). The actual processing of these requests occurs on another thread (usually the main thread, in single-threaded scenarios), which we can call the processing thread pool. In this setup, the request is swiftly processed on the processing thread, and a response is then sent back to the IO thread pool. This simplified explanation provides an overview of the request-response mechanism.

----------        -----------------       ------------------       ---------------------
| client | <----> | load balancer | <---> | request thread | <---> | processing thread |
----------        -----------------       ------------------       ---------------------

When a client sends a request to the server, it is received by the request thread pool and may have to wait until the server processes the incoming request. Delays can occur due to various reasons such as being blocked by a lengthy database query or performing resource-intensive tasks like 3D rendering. However, more frequently, delays are caused by issues like unclosed resources depleting the processing thread pool.


Illustration

Let's explore an example with a simple node server using the express framework. In Node.js, there is only one thread for processing – the main thread. Let's observe the consequences when this thread gets blocked.

const express = require('express')
const app = express();
const port = 3000;

var sleep = function(seconds) {
    var waitTill = new Date(new Date().getTime() + seconds * 1000);
    while(waitTill > new Date()){}
};

app.get('/slow', (req, res) => {
    // The sleep here signifies that process is taking a long time for whatever reason
    sleep(1);
    res.send('Slow query returns');
});

app.get('/fast', (req, res) => {
    res.send('Fast query returns');
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
});

Let's create a basic client to test the application.

var unirest = require('unirest');
var i = 0;
var j = [];
var tot = 20;
for (var i=0; i < tot; i++) {
    j = j.concat(i);
}

j.forEach(function(i) {
    console.time("No: " + i);
    unirest('GET', 'http://localhost:3000/fast')
        .end(function (res) { 
            if (res.error) throw new Error(res.error); 
            console.timeEnd("No: " + i);
        });
});

j.forEach(function(i) {
    console.time("No: " + (i+tot));
    unirest('GET', 'http://localhost:3000/slow')
        .end(function (res) { 
            if (res.error) throw new Error(res.error); 
            console.timeEnd("No: " + (i+tot));
        });
});

Output from the client:

No: 0: 31.406ms
No: 1: 31.203ms
No: 3: 31.171ms
No: 2: 31.628ms
No: 4: 31.662ms
No: 5: 31.835ms
No: 7: 31.703ms
No: 6: 32.288ms
No: 8: 32.295ms
No: 9: 32.459ms
No: 10: 1027.011ms
No: 11: 2027.326ms
No: 12: 3027.625ms
No: 13: 4027.925ms
No: 15: 5027.833ms
No: 14: 6028.303ms
No: 16: 7028.411ms
No: 18: 8030.380ms
No: 17: 9030.837ms
No: 19: 10030.692ms

The results show that the slow query significantly delays responses (e.g., the 10th request takes 10 seconds) and could potentially lead to prolonged waiting times.


Potential Issues

  1. A long-running database query blocking the processing thread and preventing timely responses
  2. An infinite loop causing a thread to be unresponsive, reducing the effective size of the processing thread pool
  3. Excessive object creation leading to excessive garbage collection, thereby obstructing the processing thread pool. This problem is common with lingering references and unclosed file pointers
  4. Deadlocks arising from threads contending for shared resources, resulting in multiple threads being blocked in the processing thread pool

This list is not exhaustive and highlights possible complications that may arise. It is crucial to address such issues promptly to ensure efficient server performance.

While older requests occupy the processing thread pool, new connections continue to be accepted by the request thread pool, potentially causing delays or even server crashes. Such scenarios indicate significant system inefficiencies.

Answer №3

There are numerous factors that can lead to a request timing out. One common reason is poor connectivity, causing delays in receiving a response.

It's unclear what specific information you're seeking and why it's needed, but if the URL being accessed does not exist, an error response will be generated swiftly. For instance, attempting to access http://asdahgo8fgasidf.com/ (a non-existent URL) would result in an error.

One scenario where timed-out requests are useful is in long polling. This involves sending a request to a server which only responds when new data is available. This approach is often used in messenger apps for checking for new messages. If a request times out, the client simply resends it to ensure prompt updates.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

Navigating with Three.JS FPS controls by moving left and right

Currently, I am working on a demo to check player controls for a FPS game. The camera rotation is controlled by the mouse, and the player can move using W-A-S-D keys. However, I am facing an issue with implementing movement left and right relative to the d ...

A collection of jQuery objects that consist of various DOM elements as their properties

Seeking a more concise and potentially more streamlined approach using jQuery. I have an object called lbl which represents a div. Inside this div, there is a span tag that contains the properties firstName and lastName of the lbl object. Here's how t ...

Eliminating Non-Breaking Spaces with the Click of a Button

Having some difficulty with the following Javascript code. I'm not very skilled in writing Javascript, so any assistance on adjusting it to replace any &nbsp; with a regular space would be greatly appreciated. Thank you function copyToClipboard( ...

Retrieving Form Data with AJAX and Javascript

When using JavaScript to generate multiple forms and embedding them into HTML using Ajax/JS, the code typically looks like this: function addProduct(product) { var html = ''; html += '<div>&apos ...

The frequency of Jquery ajax calls grows exponentially with each new request

Utilizing Jquery-ajax calls, I send information to a page and display the returned data. However, I am facing a perplexing issue: After the first ajax call is made by a user, everything appears to function normally. But if the user does not refresh the pa ...

Is recursion effective in this scenario? (javascript/node.js)

Currently, I am working on creating a TV using a Raspberry Pi and JavaScript to play the same playlist repeatedly. Although playing the files is not an issue, I am facing a challenge with the asynchronous nature of JavaScript. Below is the code that is cau ...

Having trouble accessing the loadTokenizer function in Tensorflow JS

As a beginner with Tensorflow.js concepts, I recently attempted to tokenize a sentence using the Universal Sentence Encoder in Javascript. You can explore more about it on Github Reference $ npm install @tensorflow/tfjs @tensorflow-models/universal-sentenc ...

The advantages and disadvantages of utilizing various methods to visually enhance HTML elements with JavaScript

After opening one of my web projects in IntelliJ, I noticed some JavaScript hints/errors that Netbeans did not detect. The error message was: > Assigned expression type string is not assignable to type CSSStyleDeclaration This error was related to thi ...

Sending a function along with arguments to props in TypeScript

Encountering a peculiar error while executing this code snippet (React+Typescript): // not functioning as expected <TestClass input={InputFunction} /> And similarly with the following code: // still causing issues <TestClass input={(props ...

Updating the state after receiving API results asynchronously following a function call

I am attempting to update the state asynchronously when my fetchWeather function is executed from my WeatherProvider component, which calls an axios request to a weather API. The result of this request should be mapped to a forecast variable within the fet ...

Is it possible to utilize $(this) within the $.post() function?

I seem to be having trouble accessing $(this) from inside the $.post section. It works perfectly fine outside of it. Here is the JavaScript code: $('.idea').each(function(){ var title = $(this).html(); $.post("votes.php", { t ...

Refreshing the dropdown selection to a specific option using AngularJS and either JavaScript or jQuery

Currently, I am facing an issue with resetting the select tag to its first option. I have implemented Materialize CSS for styling purposes. Despite my efforts, the code snippet below is not achieving the desired outcome. Here is the JavaScript within an ...

Executing a Jquery click event after a delay with setTimeout

I am working with an <a> element that, when clicked, triggers a handler like this: function onCummReportClick(e) { if ($(e.currentTarget).attr('href').indexOf('csv') !== -1) { { return true; } //Here s ...

Displaying empty values as zeros

Currently, I am creating a chart using Morris js. The data for the chart comes from a server and consists of dates and values. However, there are cases where certain dates do not exist in the data set. In such situations, I want to display these non-existe ...

Deleting an element from a JavaScript array

I have a collection of javascript functions that manage intervals by setting and clearing them. The intervals are stored in an array called intervals[]. config: { settings: { timezone: 'Australia/Perth,', base_url: location.p ...

Building a family tree with JavaScript's Document Object Model

My goal is to use jQuery to construct the following DOM setup: <li> <label> user <input type=radio> </label> </li> Below is the jQuery code I am trying to use. $('<input>') .attr({type:'radio&ap ...

Preventing Error in D3 Updates Caused by Invalid Path Formats

I'm encountering a problem with the d3 tree layout while dynamically adding nodes. When I add a path symbol to the node based on its type, I receive an error message "invalid path format" during updates. Both the Enter and update methods utilize the ...

Utilize Ajax to load an HTML document and append a specific value afterwards

Hey there! I have a file named personal.html with some code: <form id="form_personal"> <div class="row" style=""> <div class="row"> <div class="small-12 columns"> <label class="">Userna ...

Guide to creating a new browser tab in Java Script with customizable parameters

Here is a function I created to open a new window with a specific URL and pass certain parameters. function viewWeightAge() { var userNIC = document.getElementById("NICNo"); var childName = document.getElementById("c ...