What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine).

I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asynchronous (non-blocking) ajax call, while still achieving the result of a synchronous call without affecting UI performance.

The concept is illustrated in the following code snippet:

function do_synchronous_ajax_call(url){
    // Executes an asynchronous ajax call, which does not interrupt the user interface, but pauses the current script execution
}

var xyz = do_synchronous_ajax_call("http://...."); // Call blocks until the internal ajax request completes
// Process `xyz` here

In essence, the goal is to create a form of "artificially" synchronous ajax call that doesn't impact UI performance.

Although JavaScript lacks multi-threading support, I am still interested in exploring this possibility.

This marks the third inquiry on this topic.
My previous questions are as follows:
how to block on ajax call (I want it to block)
can a synchronous (blocking) ajax call block the browser's UI?

Answer №1

In order for the user interface to be refreshed, control must be returned to the browser through the use of asynchronous code (or any code that promptly returns)

Answer №2

Why bother "blocking" when you can just let things be? It appears that the concept of asynchronous flow might still be elusive to you. Rather than waiting around, you should define what actions to take once the data is ready. Arrange your request with a callback function that will execute the remaining code, send off the request, and step away from JavaScript, allowing the browser to carry on until it's time for your code to resume.

Answer №3

To ensure a globally available lock in your code, consider utilizing a boolean variable within a global context or an object that contains various options and objects at a universal level.

function handle_ajax_call(url)
{
    if (!is_locked)
    {
        // perform actions here
        is_locked = true;

        xmlhttp.onreadystatechange = processCallback;
    }
}

function processCallback() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
         // additional actions here
    }

    is_locked = false;
}

If you transition to using jQuery AJAX, you will have access to a wide range of framework events and methods such as "beforeSend", allowing you to implement a similar locking mechanism alongside the "done" event for better control.

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

Having difficulty choosing an element with protractor's virtual repeat functionality

Initially, I successfully used ng-repeat to select an element. However, the developers have since implemented virtual repeat which has caused the following code to stop working: expect(stores.listStores(0).getText()).toContain('Prahran'); expect ...

React Native's fetch function appears to be non-responsive

I am experiencing an issue where the fetch function does not seem to fire in my React Native component: import { Button } from 'react-native'; export function Test() { function submit() { console.log('submit'); fetch('h ...

Is there a way for me to extract the true text content that is concealed within the page source code?

Is there a way to extract the hidden text "2015-10-31" from a webpage, even though it is not visible in the page source? I am able to scrape the right side of the HTML, but I need to access the value on the left side. I have tried using Selenium to automat ...

What are the steps for importing KnockOut 4 in TypeScript?

It appears straightforward since the same code functions well in a simple JS file and provides autocompletion for the ko variable's members. Here is the TypeScript code snippet: // both of the following import lines result in: `ko` undefined // impo ...

Hello, I'm looking for assistance with this ReactJS code. Is there anyone who can help me

I am not receiving any output and also not encountering any errors, how can I resolve this issue? import React from 'react' function Array() { function myConcat() { const Villain = ["Harley Quinn", "Brainiac", "Deathstroke"]; cons ...

NPM is having trouble locating a shell script

An error is encountered when running npm run build: '.' is not recognized as an internal or external command, operable program or batch file. Here is the npm file that contains relevant scripts: "scripts": { "postinstall": "jspm instal ...

Extracting keys and values from a JSON string for analysis

My current code for the service now rest outbound call is functioning correctly. However, I am facing issues while trying to parse the JSON body in the second REST call and fetch values in the desired table format. try { var r = new sn_ws.RESTMessageV2 ...

How should we structure our JavaScript code: MVC or self-rendering components?

I'm in the process of developing a highly JS-centric web application. The bulk of the work is being carried out on the client side, with occasional syncing to the server using AJAX and XMPP. This is my first venture into creating something of this ma ...

Best Practices for Implementing JSON.stringify() with an AJAX Request

While I have a limited understanding of ajax and JSON, I am aware that using JSON.stringify in an ajax call can sometimes be beneficial. The ajax call below is functioning properly, whereas the one following it with the stringify method is not. I am unsure ...

Divide Angular ngFor into separate divs

Here is an example of my current array: [a, b, c, d, e, f, g, h, i] I am aiming to iterate through it using ngFor and split it into groups of 3 elements. The desired output should look like this: <div class="wrapper"> <div class="main"> ...

Exploring the functionality of arrays in Jest's cli option --testPathIgnorePatterns

Looking to exclude multiple folders, one in the src folder and another in node_modules, when using the --testPathIgnorePatterns option. Does anyone have an example of how to use this pattern effectively? I am unable to configure an array in the package.js ...

Placing an icon to the left of the primaryText within the <ListItem> component of Material UI

Seeking to enhance a <ListItem> from React Material UI that currently displays a checkbox on the left side. My goal is to insert an image or icon between the checkbox and the title, positioned to the left of the title. Upon reviewing the documentatio ...

Ways to transfer a state from the child component to the app component

I have 2 different components that contain sub-components within them. In one of these components, I'm trying to figure out how to transfer the click event from the sub-component to another component so that it can render an entirely new component for ...

Using setInterval on a batch of freshly generated div elements

I am interested in creating a small website where I can display multiple clocks for various time zones. However, I have encountered an issue with the setInterval function. Below is the code snippet: function addClock () { $("#container").append('& ...

Inadvertent scroll actions causing unexpected value changes in Material UI sliders

I am currently working on a React application that utilizes Material UI, with slider components integrated throughout the interface. However, I have encountered an issue when using a touch screen device - unintentional changes to the slider values occur wh ...

Comparing values inputted from JavaScript using PHP

I am passing values from PHP to a script. <img src=\"images/add.jpg\" onclick='add_program_user(".$value['id_program'].",".$value['min_age'].",".$value['max_age'].")' onmouseover=\"this.style.curso ...

Leveraging AngularJS for a Windows store app

After attempting to integrate AngularJS into my Windows store application, I came across a few recommended solutions: Unfortunately, these solutions did not work as expected. While I didn't encounter the Unable to add dynamic content error, AngularJS ...

Instantly summing up two numbers with javascript

In my web development work using Visual Studio 2008, I encountered an interesting challenge. On a webpage, I have three textboxes labeled "Price," "Quantity," and "Amount." The task at hand is to calculate the value of "Amount" by multiplying the values ...

Omit node_modules from typescript compilation using gulp-typescript

Having trouble running a gulp task to compile my typescript due to dependency-related errors. /content/node_modules/@angular/core/src/facade/lang.d.ts(12,17): error TS2304: Cannot find name 'Map'. /content/node_modules/@angular/core/src/facade/l ...

What is the best way to change a JSON string into an array of mysterious objects?

I am currently working on a flashcard generator project and I am dealing with a JSON String that is quite complex. The JSON String contains multiple arrays and objects structured like this: data = [{"front":"What is your name?","back":"Billy"},{"front":"H ...