The readystatechange event of XMLHttpRequest triggers before the completion of the current script

Can someone explain why, in the code snippet below, line (a) triggers the 'readystatechange' event and logs this.readyState to the console before logging "ends" at line (b)? Shouldn't the callback be placed in the event queue and only executed after the main script finishes?

    const somePath = 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange';
    const xhr = new XMLHttpRequest();
    console.log(xhr.readyState); // This will output 0
    xhr.addEventListener('readystatechange', function() {
        console.log(this.readyState)
    }); 
    xhr.open('GET', somePath, true); // (a) Will output 1 to the console
    console.log('ends'); // (b)

Answer №1

In this specific context, events are handled synchronously rather than asynchronously. When xhr.open is executed and the readystatechange event occurs, the code within the xhr will process attached listeners one by one in a synchronous manner.

The structure of the code can be visualized as follows:

const obj = (() => {
  const listeners = [];
  const addListener = fn => listeners.push(fn);
  const doSomething = () => {
    console.log('doing something');
    listeners.forEach(listener => listener());
  };
  return { addListener, doSomething };
})();
obj.addListener(() => console.log('listener running'));
obj.doSomething();
console.log('end of main thread');

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

How can I use a string argument in JavaScript to sort an array of objects by that specific value?

Currently, I am implementing React and facing a challenge with creating a reusable sorting component. This component is meant to sort an array of objects based on a specific property field. For instance, imagine having an array of objects with properties a ...

Simulation of documentElement language property in Jest

I am currently attempting to manipulate the documentElement lang property for my testing purposes, but I am struggling to find a solution. I have tried defining setupFiles in Jest config, which allowed me to define it but did not give me the option to chan ...

Explore Marker GeoCharts within AngularJS to enhance visualization capabilities

I am trying to customize the markers on a GeoChart similar to the one shown in this example. Could you please guide me on how to add the mapsApiKey in Google GeoChart using the ng-google-chart directive? Here's an example code snippet: var chart = {} ...

Callback function not being triggered in Jquery's getJson method

I am currently faced with a javascript conundrum. Below is the snippet of code that I have been working on: $.get("categories/json_get_cities/" + stateId, function(result) { //code here }, 'json' ); ...

Encountered a snag with submitting data via AJAX: received an error message stating

I created this custom script for a contact form on my website, and it seems to be working fine. However, I'm encountering an issue where instead of storing the data in my database, all I get is [object HTMLCollection]. Can someone please explain wh ...

Is there a way to update a single document in a MongoDB database using Mongoose without directly referencing the document?

Let's say I have an example: 1 //Let's say I have an example 2 3 app.post('/update', validate, async (req, res) => { 4 const {title, description, post_id} = req.body; 5 6 // Updating one of them if they exist 7 ...

Can you explain the distinction between the GenerateSW and InjectManifest choices within the vue ui pwd configuration?

Currently utilizing @vue/cli for building a vue project. I have initiated vue ui to access the vue UI and am in the process of customizing various available options. https://i.sstatic.net/h77AE.png Within Configuration -> PWA, I have come across the a ...

Is it possible to apply the active class to the current list menu item in Mark using server-side techniques instead of client-side JS

When a menu item is clicked, I want to add the active class to that specific menu item. For example, if someone clicks on the contact page, the contact option in the menu should receive the active class. I am currently working with NodeJS and Koa. Below is ...

What's the best way to ensure uniform spacing between the list items in this slider?

When using appendTo, I've noticed that the spacing between items disappears. I've tried adjusting the padding-bottom and left properties with no success. Does anyone have a suggestion for how to fix this issue? I'm at a standstill. $(&a ...

Tips for troubleshooting and resolving the npm ERR! code E404 issue in Vue.js when implementing a datepicker

I am a newcomer to Vue.js and I am currently exploring the use of a datepicker from However, upon importing the script for usage, I encountered the following message: 'VMdDateRangePicker' is declared but its value is never read.ts(6133) Cou ...

What is the process for determining the remaining number of divs after deletion?

Within my HTML document, I have a total of eight div elements. Through the use of jQuery, I managed to extract the number of these divs and display it within the .num div. However, when I proceed to delete one of the div elements by clicking the designate ...

When multiple pages are open and one page remains idle, the user session will time out due to the timer implemented in JS/JQuery

I currently have a user activity monitoring system in place on my webpage. When a user is inactive (i.e. doesn't move the mouse) for 30 minutes, a warning is displayed informing the user that their session will expire soon. If the user does not intera ...

When using nextjs, there is an issue that arises when attempting to define the property 'id' using context.params.id. This results in

Attempting to retrieve data from a JSON file (response.json) hosted on localhost:8000/response.json. Below is the code snippet from pages/test.js: import React from "react"; import Link from "next/link"; import Image from "next/ima ...

How to sort Firebase real-time database by the child node with the highest number of

I am working on a database feature that allows users to 'like' comments on posts. Is there a way for me to sort the comments based on the number of likes they have? Although I am aware of using .orderByChild(), my issue lies in not having a sep ...

In JavaScript, it is not possible to retrieve the maximum or minimum value of an array

Hey there! I'm having some trouble finding the minimum and maximum values in an array. Can you help me figure out what's going on with my code? var repeated, studentsArray = [], marksArray = []; while (repeated !== 'n' && r ...

What is the best approach to store an array of Web Api data in a nested mongoose schema following a child-parent schema structure?

My goal is to store the information retrieved from a Web Api, which contains multiple arrays of data, in order to populate a stock chart. Every time I input a symbol and click the "Get Quote" button, it should gather data from the Web Api and save it withi ...

Decode PDF417 barcode images with ease using HTML and JavaScript on both desktop and mobile web browsers

Looking to utilize JavaScript to decode PDF417 type barcode images? If you're encountering Zxing plugin issues in mobile browsers but it works well on desktop browsers with https://github.com/PeculiarVentures/js-zxing-pdf417, consider alternative sol ...

Copy the AJAX response from a JQuery request to the clipboard seamlessly without requiring the user to manually click a button

I'm attempting to automatically copy a portion of a JSON AJAX response to the user's clipboard. When the user submits a form by clicking a button, I want the response to be copied without any additional interaction required. This is my progress ...

The PHP function is not successfully receiving a value from the AJAX call to be entered into the Database

I've been struggling with a piece of code lately, trying to pass the value 1 to my database when a user clicks the "collect coins" button. The goal is to reset the column "dailyfree" every day at 12 pm so that users can click the button again on the n ...

What's causing me to encounter two canvases while implementing PIXI.js in my Next.js project?

I'm facing a challenge in my game development project that utilizes PIXI.js within a Next.js setup. Currently, I am experiencing an issue where the webpage is displaying two canvases instead of one, leading to unexpected rendering issues and impacting ...