AJAX working concurrently across multiple threads

After learning that JavaScript is single-threaded (as discussed in this question: If Javascript is not multithreaded, is there any reason to implement asynchronous Ajax Queuing?), I started to explore how this concept applies to my developed application. Here is a snippet of the code:

function GetSQLTable() {
        var str = $("#<%=fieldDatabaseReferences.ClientID%>")[0].value
        var res = str.split(",");
        $("#LoadingImage").show();
        $("#LoadingImage2").show();

        for (var i = 0; i < res.length; i++) {
            (function (i, res) {
                setTimeout(function () {
                    GetSQLTable2(i, res.length, res)
                }, 0);
            })(i, res);
        }
    }

function GetSQLTable2(i,reslength,res) {
            //if (i == 0)
            //{
            //    var start = new Date().getTime();
            //}
        var div = document.createElement('div');
            div.id = "div" + i
            document.getElementById('info_div').appendChild(div);

            var PossiblesPage = false;
            $.ajax({
                type: "POST",
                url: "PrimaryNominalAjax.aspx/GetSQLTable",
                data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '", usn: "' + $("#<%=fieldUSN.ClientID%>")[0].value + '", requester: "' + $("#<%=fieldRequester.ClientID%>")[0].value + '", reason: "' + $("#<%=fieldReason.ClientID%>")[0].value + '", rrd: "' + $("#<%=fieldRRD.ClientID%>")[0].value + '", review: "' + $("#<%=fieldReview.ClientID%>")[0].value + '", possibles: "' + PossiblesPage + '",linkno: "", urn1: "", urn2: ""}',
                contentType: "application/json; charset=utf-8",
                timeout: 80000000,
                dataType: "json",
                success: OnSuccess(i, reslength),
                error: OnError,
                failure: function (response) {
                    alert('there was an error loading the webpage')
                }
            });
        }

The server side populates the fieldDatabaseReferences. The AJAX requests data from multiple local databases, with the information being displayed on the screen as it becomes available.

Given that the calls to various database servers are asynchronous, could this potentially have a multi-threaded effect?

Answer №1

Did you know that JavaScript operates on a single-threaded system? This means that when asynchronous events occur, they are placed in a queue until the thread becomes idle. Let's take a look at an illustrative example:

var proceed = true;
var limit = Date.now() + 5000;    // set limit five seconds from now
setTimeout(function(){
    proceed = false;             // asynchronously set the 'proceed' variable to false
}, 1000);                       // after one second
while(proceed && Date.now() < limit); // loop until both conditions are true
console.log("proceed:", proceed);  // output 'proceed: true' (initial value)

Would you guess that the loop terminates after one second? Not quite. In reality, it would continue endlessly (if Date.now check was not included). The fact that the console logs true affirms that the timeout hasn't been triggered yet, as it patiently waits for the initial block to finish.


Regarding your scenario, the sequence of execution plays out as follows:

/* note: functions never run concurrently */
RetrieveData();
/* functions queued via setTimeout run sequentially */
RetrieveDataUpdate(0, ...);
RetrieveDataUpdate(1, ...);
RetrieveDataUpdate(2, ...);
/* AJAX responses are processed one after another, not necessarily in initiation order */
OnDataReceived(2);
OnDataReceived(0);
/* The JavaScript thread may pause during callbacks */
OnDataReceived(1);

Additional sources for understanding JavaScript timers and the event loop:

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

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

Encountering a 404 Error while using GetStaticPaths in NextJs

Having issues with Next JS dynamic routes resulting in a 404 Error. Initially attempted debugging by setting it up dynamically, then manually at http://localhost:3001/question/62e7b69ca560b1c81aa1a853 but still encountering the same issue. Tried toggling f ...

Start by executing the function and then proceed to upload a static file

Here is the code I am working with: var express = require('express'), app = express(); app.use(express.static(__dirname + '/static')); app.get('/', function(req, res) { //??? }); app.listen(80); I need to first ex ...

Dynamic jQuery slideshow featuring a variety of animations applied to individual elements

I'm interested in creating a custom jQuery slideshow that involves animating HTML elements within each slide differently. Specifically, I would like to have 3 divs sliding out to the left with delays on 2 of them, and then being replaced by equivalen ...

"Combining multiple attributes to target elements while excluding specific classes

My dilemma lies in the following selector that identifies all necessary elements along with an extra element containing the "formValue" class which I aim to omit $("[data-OriginalValue][data-OriginalValue!=''][data-TaskItemID]") ...

Remove a function tied to an element on a page that has loaded

I have been struggling to remove a function that is attached to an event using both unbind and off, but unfortunately, it has been unsuccessful. To illustrate this issue clearly, I have created a replica on jsFiddle here. The recreated problem closely res ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...

Clicking on Rows in DataTables: Enhancing

I have been utilizing the jquery datatables plugin, and have encountered an issue with the row click functionality. Strangely, it only seems to work on the first page of the table. When I navigate to any subsequent pages, the row click fails to respond whe ...

Storing user feedback in database using ajax

I have encountered a common issue in this thread, and although it has been discussed multiple times, I am still unable to solve my problem. My struggle lies in sending and fetching data from comment.php to insert.php. Below is the code from my comment.php ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

Implementing a sorting mechanism for ajax data retrieval

Currently, I am using the code below to save HTML created with jQuery in a database and retrieve it later: $('div[read]').each(function(){ var kelas = $(this).attr('kelas'); $.post('admin.php',{kelas:kelas,id:id},func ...

Is your JQuery Gallery experiencing issues with the next button function?

I'm working on developing a simple gallery using JQuery. The main concept is to have all image files named x.png (where x is a number), and the program will then add a number to the current one, creating x+1.png and so forth. Here's the code I ...

Content within iframe is failing to load correctly on both Firefox and Internet Explorer browsers

On my website, I have 4 iframes embedded in 4 different tabs. I've noticed that the content is being cropped when viewed on Firefox, but it loads properly when using Chrome. Strangely, if I manually reload the iframe, the content displays correctly. T ...

Include a new key and its corresponding value to an already existing key within FormData

I have a form that includes fields for title, name, and description. My goal is to submit the form values using an API. To achieve this, I am utilizing jQuery to add key-value pairs to the FormData variable: formdata.append('description_text', jq ...

Could you please explain the specific distinctions between pipe and map within Angular 7?

After extensive research, I'm still struggling to understand the distinction between pipe and map in Angular 7. Should we always include a pipe in Service.ts file in Angular 7? Appreciate any clarification on this matter. ...

Tips for inserting text to the left rather than the right using Jquery

I recently came across this code snippet shared by some helpful users on stackoverflow and it has been working perfectly for me. However, I do have a couple of queries regarding its functionality. Firstly, how can I ensure that the current selected option ...

What is the significance of using the variable name "$scope" in coding?

As a newcomer to Javascript, I recently finished reading the book Eloquent Javascript and am now delving into AngularJS from O'Reilly. While working on a code snippet provided in the AngularJS book, I encountered hours of frustration trying to figure ...

Is there a way to accomplish this without using settimeout?

Whenever the Like button is pressed, I want to trigger the loading process I expect to see LOAD_POST_SUCCESS immediately after LIKE_POST_SUCCESS Pressing the Like button should initiate the load process After LIKE_POST_SUCESS, I want to see LOAD_POST_SU ...

Using jQuery/AJAX for nested functions, as well as utilizing the Clone and Cufon properties

Currently utilizing Cufon to easily transform fonts into canvas. This script specifically transforms H1 headers: Cufon.replace('h1', { fontFamily: 'SuperMegaArial2010' }); While everything is functioning correctly, I encounter an is ...

What steps can I take to prevent the [Vue warn]: Potential infinite update loop detected in a component render function issue in my VueJS project?

What are some tips to prevent an infinite update loop in a component render function using VUEJS? I have created a simple show password button with the following structure: <div class="mt-4 switchContainerGenPassword"> <div class="switchGene ...