Delayed execution of Ajax request

Currently watching a Youtube video that explains the Call Stack and Event loop when dealing with Async events like Ajax calls. According to the video, JavaScript execution occurs line by line. Let's try running a sample program:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(xhttp.responseText);
  }
};
xhttp.open("GET", 'https://httpbin.org/get', true);
xhttp.send();

let i = 1;
while (i < 1000000000) {
  i++;
}

console.log(i); 

Based on my understanding from the video, the JS Engine will place the Ajax call in the Call Stack and execute it. Since the Ajax call takes some time, the callback will be moved to Web APIs by the browser and the code continues executing (in this case, the while loop). Once the Ajax call is complete, the Web APIs will add the callback to the Task Queue. If the Call Stack is empty, the Event Loop will push the callback back onto the stack for execution. In our example, I purposely made the loop count large to make the Event Loop wait until the while loop finishes even though the Ajax call is done. However, when I ran the program, the Ajax call was only made after the while loop completed. This raises the question of why we put the Ajax call before the while loop. I expected the Ajax call to be triggered immediately but the response to be printed after the loop finished. Is there something that I have misunderstood?

Answer №1

Allow me to attempt to address this query, and I welcome any additional insights or corrections as they would contribute to our mutual learning.

AJAX stands for Asynchronous JavaScript And XML, clearly indicating that the function operates asynchronously. The explanation in the linked video provides a comprehensive understanding of asynchronous codes, particularly highlighting the 'blocking' aspect of JavaScript.

In the provided scenario, the AJAX call is placed in the stack; however, being an asynchronous function, it does not halt the execution of the subsequent code, such as your while loop. The while loop, on the other hand, is synchronous and will pause all processes until it completes (resulting in the blocking of the asynchronous function).

Given that console.log() executes faster than the AJAX result, the console output will appear first, followed by the outcome of the HTTP request.

Source: https://www.youtube.com/watch?v=8aGhZQkoFbQ&t=412s

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

Add JavaScript code to your project without bundling it as a module

Is it possible to incorporate a JavaScript library into webpack that is not structured as a UMD-compatible module (AMD, CommonJS)? I want the library to be included in a <script> tag only when necessary and managed by webpack without passing through ...

Adjust the browser zoom level to default when navigating to a new page

My mobile site uses ajax to load pages, and I'm looking to implement a feature that resets the zoom level when a page changes. Is there an effective way to detect if a user has zoomed the view while browsing a page? Currently, I have been able to ch ...

Stagnant className in map persisting despite changes being made

I am in the process of updating my react className based on changes to the active status within the sites variable, which is iterated over with a map function. The issue I'm facing is that the 'inactive' className persists even when the act ...

Searching for specific values within data attributes using jQuery wildcards

I am currently utilizing the data_attribute on this page and have the following elements with data attributes. No. 1.<div class="row hidden" data-party-registration-source-type-id="1"> 2.<div class="row hidden" data-party-registration-source- ...

Unable to locate the module 'winston'

Developed a small module that utilizes winston for logging purposes. Installed winston using sudo npm install -g winston (since it's on a virtual machine, not too concerned with sudo permissions). NPM log: <a href="/cdn-cgi/l/email-protection" c ...

What is the best way to transfer the text from an input field into a paragraph when a button is

For a school project, I am developing a website focused on time management. My goal is to create an input text box that, when the "add task" button is clicked, transfers the text inside it to a paragraph or p2 element and then moves the input field down. ...

Adding an image to a jQuery class name on the fly

I am attempting to add an image before a div by using its className with jQuery. function insertImage(obj) { var dynamicClass = $(obj).prop("className"); After retrieving the classname, I now encapsulate it in single quotes and add a dot to access t ...

Guide to emphasizing text with hover effects and excluding whitespace (javascript)

Currently, I am utilizing jQuery for hover highlighting purposes. However, I am facing an issue where the entire div gets highlighted instead of just the text. I attempted to use an "a tag" but don't want a reference link. I know this should be a simp ...

What is the best way to pass and retrieve parameters in a Spring application?

I am attempting to perform a simple task using AJAX, sending a request with either a GET or POST method. The goal is to send 2 parameters in JSON format and receive them back in a response. However, I keep encountering a 400 error and other unknown errors ...

Retrieve a JSON file from the local file system using AngularJS

I recently started learning AngularJS and I am trying to read a JSON file from my local system. However, when I attempt to do so, I encounter an exception error that says: "Access to restricted URI denied XMLHttpRequest." Here is the code snippet: var de ...

Save a collection of controller instances within a separate controller in AngularJS

I am in need of an angular example where one controller wraps another. For instance, I am looking to divide some logic between EndpointListController and EndpointController. EndpointListController will handle retrieving data from storage, along with funct ...

Loading a local FBX file in Three.js without the need to upload it

When attempting to load files selected by users in an HTML input, I encountered a problem with the loader expecting a URL in Linux style. I have tried various methods such as using a blob as a URL object, providing raw data to the FBX loader, and even usin ...

Creating a fresh array by applying a filter and assigning keys

I am facing an issue with my array structure, it looks like this, [ [ "Show/Hide", "P000", "MAX-CT05 FVM2-", "S", 1532, -9.5929406005, null, null, ...

Creating a series of image files from CSS and Javascript animations using Selenium in Python

Looking to convert custom CSS3/Javascript animations into PNG files on the server side and then combine them into a single video file? I found an interesting solution using PhantomJS here. As I am not very familiar with Selenium, adapting it for use with S ...

Only on mobile devices, Material-UI components spill over the screen

Update: This issue is isolated to one specific page. Other pages within the website are displaying correctly. Recently, I developed a web page using React and Material-UI. The main components utilized are Grid and Container. While the layout appears fine ...

A guide to deactivating the Material UI Link API element

Previously, I relied on Material UI's Button component with a disable property that allowed the button to be disabled based on a boolean value. However, I now want to use the Material UI Link component, which resembles a text link but functions like a ...

Angular and Three JS collaboration leads to misplacement of canvas rendering

Currently in the process of developing code for a website, I am attempting to integrate Three JS with Angular. After conducting some research, I have found that this combination is feasible and I have successfully merged these two libraries. However, I am ...

Gather data from various textboxes and combine them into a unified string with the help of JavaScript

I am currently facing a challenge where I need to extract the values from multiple textboxes and combine them into a single string. This string will then be sent to my PHP processing page for insertion into a database table. The textboxes mentioned above ...

Transforming the hide/show functionality from JQuery to Vue

I created some hide/show panels using jQuery that I want to implement in Vue. However, when I try to integrate the jQuery functions into Vue, the functionality doesn't seem to work properly. The panels are not hiding/showing as expected. Does anyone ...

"Troubleshooting problem with fetching JSON data for Highcharts

As a relative newcomer to web development, my usual focus is on server-side work. Currently, I'm diving into a fun little electronic project where a Netduino server handles JSON requests within my LAN. The JSON response format from the Netduino looks ...