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

Tips for extracting valuable insights from console.log()

I'm currently utilizing OpenLayers and jQuery to map out a GeoJson file containing various features and their properties. My objective is to extract the list of properties associated with a specific feature called "my_feature". In an attempt to achi ...

Error: The API_URL_KEY variable has not been declared

hardhat.config.js require("@nomicfoundation/hardhat-toolbox"); /** @type import('hardhat/config').HardhatUserConfig */ module.exports = { solidity: "0.8.18", }; /* @type import('hardhat/config').HardhatUserConfig* ...

Concealing the sidebar in React with the help of Ant Design

I want to create a sidebar that can be hidden by clicking an icon in the navigation bar without using classes. Although I may be approaching this incorrectly, I prefer to keep it simple. The error message I encountered is: (property) collapsed: boolean ...

Customize the appearance of Woocommerce's blockUi feature with your

During an Ajax request, blockUI adds a style to the blocks of the checkout form and cart with "background: '#fff'". However, my entire website theme is black and I do not want the background color of the blocks to be white. Is there a way to remo ...

After redirection to a new page, the Ionic-vue menu malfunctioned

I have developed a reusable header component named Header, which contains an IonMenu component for consistency across pages. The menu is associated with the IonRouterOutlet as per the documentation, but I am encountering an issue when navigating between pa ...

Initiate AJAX request when searching (utilizing the pg_search gem)

I've successfully implemented a search form using the pg_search gem, inspired by Railscast #343. Despite my efforts, the page always reloads on search queries. I attempted adding :remote => true to the form and utilized a respond_to block in the con ...

Is there a way to deactivate the click function in ngx-quill editor for angular when it is empty?

In the following ngx-quill editor, users can input text that will be displayed when a click button is pressed. However, there is an issue I am currently facing: I am able to click the button even if no text has been entered, and this behavior continues li ...

Ways to rearrange an object with javascript

I am looking to restructure my object by removing a nesting. How can I achieve this using JavaScript? Actual: var a = [ { clickedEvents: { 'event-element': 'a', 'event-description': & ...

What is the best way to set up the correct pathway for displaying the image?

I'm currently facing a challenge with displaying an image from my repository. The component's framework is stored in one library, while I'm attempting to render it in a separate repository. However, I am struggling to determine the correct p ...

Unable to transfer the component between components

This is the code I have: index.js: import React from "react"; import ReactDOM from "react-dom"; import {dest, People} from './components/people'; import json from './people.json'; function initFromJson() { let names = []; for(let ...

The route seems to be downloading the page instead of properly rendering it for display

I'm facing a simple issue with my Express page - when I navigate to the FAQ route, instead of displaying the page it downloads it. The index page loads fine, and the FAQ page is the only other page available at the moment. I am using EJS templating, a ...

Encountering NodeJS server issues with 505/404 errors while fetching partials

I am currently working on an application built using the M.E.A.N stack. For routing, I have implemented Angular Ui Router. However, I am encountering difficulties in correctly routing partials. The link for the main view is functioning properly with the ...

Where can I find the JavaScript code that controls the button function?

Is there a method to identify the trigger that activates a button's specific action and page refresh, such as this example: <input type="submit" name="name" value="some value" id="mt1_main_btn" class="btn_next"> Simply copying the button does ...

What could be the reason behind the app.get middleware not functioning properly following the app.use middleware in ExpressJS?

My server.js file includes the following code. However, I've encountered an issue where the code in app.get() function works fine when the app.use() middleware is commented out. But, when both are included, the get request doesn't seem to run. An ...

Navigating through pages using Jquery's show and hide functionality

How come my item is not returning? I used the .show() method on the item. <div id="back">< back</div> <div class="item">item</div> <div class="content">My content</div> $(function(){ $('.item').on(&apo ...

Unexpectedly, the jQuery get function retrieves the entire webpage

I'm encountering difficulties when using .get requests to update elements through page load or button press. Here is the code snippet... $(document).ready(function() { //updateVariable(); $('#dannychoolink').html('<?php dan ...

Tips for properly styling Ajax Response Data?

I recently started working with Ajax and was able to successfully retrieve cross-domain data using a proxy. The output that I received is as follows: {"error":"\r\n\r\n\r\n\r\n\r\n\r\n\r&bso ...

Updating the DOM through Long Polling allows us to maintain existing attributes in jQuery Plugin

UPDATE: The functionality is all set; the pushes are working. The only issue I'm facing is that each push resets the #load_info div to empty. Is there a way to retain the original content inside the div, even though the content will be an updated vers ...

Can a Spring MVC controller method return a JSONArray using @ResponseBody annotation?

I am facing an issue with AJAX while trying to load a URL that should return data from my controller in JSONArray format. However, when the call is made, I encounter a 406 not acceptable error. Is there any way to resolve this using @ResponseBody? Despite ...

Contrasts between the storage of data in a static function versus a static object

Trying to figure out the best way to reset a react class component back to its initial state, I came across two different implementations. In my own version, I created an object with initial values and set the component's state equal to it: // My imp ...