Interact with the DOM dynamically for every Ajax response without causing the user interface to freeze

I conduct a for loop for every request that is sent..

for (let k = 0; k <= 1000; k++) {
    $.ajax({
        url: `127.0.0.1/index?value=${k}`,
        method: `get`,
        beforeSend: function() {
            // any action..
        },
        success: function(response, status, xhr) {
            $('#response').append(response);
        }
    });
}

Nevertheless, as the for loop progresses from 0 to 1000 (this number may vary, it's just for illustrative purposes.) the user interface becomes unresponsive, and the responses to requests are not displayed in the DOM.

<div id="response"></div>

How can I improve this? Ideally, each ajax request should dynamically display the result in the response div (or synchronously)

Is there a straightforward solution that can help me achieve this?

Answer №1

If you want to make individual ajax calls sequentially, you can use the following approach:

const fn = j => $.ajax({
  url: `//127.0.0.1/index?value=${j}`,
  method: `get`,
  beforeSend: function() {
    // perform any action..
  },
  success: function(response, status, xhr) {
    $('#response').append(response);
    if (j < 1000) {
      fn(j + 1);
    }
  }
});
fn(0);

By following this method, you ensure that the order of the results is maintained.

You can also modify the code to make multiple requests at a time, but ensuring result order may require additional changes.

Here is an alternative solution where you specify the starting index, ending index, and number of requests to be made simultaneously - with flexibility in result order:

const fn = async (index, max, count) => {
    const promises = [];
    for (i = 0; i < count; ++i) {
        promises.push($.ajax({
            url: `//127.0.0.1/index?value=${i+index}`,
            method: `get`,
            beforeSend: function() {
                // perform any action..
            },
            success: function(response, status, xhr) {
                $('#response').append(response);
            }
        }));
    }
    await promises;
    index += count;
    if (index <= max) {
        fn(index, max, Math.min(count, max + 1 - index));
    }
};
fn(0, 1000, 10);

Lastly, here's another variation that ensures the sequence of the results stays intact regardless of their return order:

const fn = async (index, max, count) => {
    const promises = [];
    for (i = 0; i < count; ++i) {
        promises.push($.ajax({
            url: `//127.0.0.1/index?value=${i+index}`,
            method: `get`,
            beforeSend: function() {
                // perform any action..
            }
        }));
    }
    const results = await promises;
    $('#response').append(results.join(''));
    index += count;
    if (index <= max) {
        fn(index, max, Math.min(count, max + 1 - index));
    }
};
fn(0, 1000, 10);

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

display the hidden box contents when clicking the button within a PHP loop

I am attempting to create a simple e-commerce site for learning purposes, but I encountered an issue when trying to display information upon clicking a button. The button does not seem to trigger any action as expected. It is meant to reveal text from the ...

Using Ajax with MySQL can be quite time-consuming

I am working with two PHP pages and one JavaScript page. In my database, there is one row with 2 columns. Here is the main PHP code: <html> <head> <title>Hello!</title> <script type="text/javascript" src="script/jquery-2.0. ...

Tips for identifying the extreme points (minimum and maximum) within a fluctuating interval

With an array of length 200, a new number is added to position [0] every second, pushing the other values up one position in the array. I am looking for a way to determine the maximum and minimum values of the entire array each time a new number is added. ...

Dynamic Element with Mousewheel Event

Simply put, I am attempting to attach a 'mousewheel' event to a div that contains a scrollbar. My code functions properly when used outside of the plugin I developed, but as soon as I convert it into a plugin, it stops working. I tested changing ...

Utilize CSS with dynamically created elements

I am currently figuring out how to use my .each() function with a $(document).ready and a click event. Here's what I have so far: $(document).ready(function(){ $(".help-inline").each(function() { $(this).css('display', 'none&apos ...

Adding real-time value to AngularJS directives without triggering reassessment

Seeking guidance on utilizing an AngularJS directive as an HTML element, with the intention to provide it two values. One will be fetched by iterating through a collection, while the other will be derived from that value: <mydirective myval="val" mymag ...

An error popped up as I attempted to load an existing design within the vue-email-editor

https://i.stack.imgur.com/0ObU5.png Check out the code snippet below for the function I have created: editorLoaded() { this.$refs.emailEditor.editor.loadDesign(this.emailJson); console.log('editorLoaded'); }, ...

Ensure that you include validation in the ajax request when loading the message content from a separate file

ajax code for adding data to the database <script type="text/javascript"> $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var dataString = 'content='+ textcontent; if(textcontent=='') ...

Nested function and the process of breaking out of the parent function

Is it possible to exit out of the main/parent function when I am in a function that was called from inside another function? For example: function(firstFunction(){ //stuff secondFunction() // code continuation if second function doesn't ...

Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Eve' } ] My goal is to locate an object by its id and append a ...

Tips on employing useState within useEffect?

Attempting to refactor my component from react.component to hooks has been a bit challenging. I am struggling to properly utilize the state variable offsetTop. It seems like the value is not being set when needed. In my first attempt: const [offsetTop, se ...

Error while compiling Q_PROPERTY

Current Environment : Qt 5.8 MSVC2015 64bit, Windows 7 64 bit. I have successfully called a C++ method from Java Script. However, I encountered an issue when trying to retrieve the return value of the C++ method in JavaScript. To address this, I attempt ...

Updating the mat-icon in a row when a button is clicked

I am currently working on implementing the mat-table in my project. I am facing an issue where I need to change the mat-icon of a button based on a click event, but I only want this change to apply to a single row in the table. At the moment, I am able to ...

After retrieving a value from attr(), the object does not have the 'split' method available

I need to implement the split method on a variable fetched using attr. This is the code snippet I am attempting: $(document).ready(function() { $('.some_divs').each(function() { var id = $(this).attr('id'); var ida = ...

By selecting "open in a new window" on an Ajax.ActionLink within an MVC partial view, the entire page can be refreshed

Hello there, in my HomeController I have an action that returns a strongly-typed partial view. public virtual ActionResult ImportShow(String id, String menuID, string articlegroupID) { GroupMenu p_GroupMenu = new GroupMenu(); ...

Retrieve selected value from HTML input with datalist and use it as an argument in a method

I have a datalist in my HTML input where I need to pass the selected value into JavaScript / Angular. It must be passed because the datalist is being used in an HTML table with multiple entries. Most examples I've come across show how to grab the valu ...

I am having trouble getting my AngularJS client to properly consume the RESTful call

As I venture into the world of AngularJS and attempt to work with a RESTful service, I am encountering a challenge. Upon making a REST call to http://localhost:8080/application/webapi/myApp/, I receive the following JSON response: { "content": "Hel ...

Ways to swap webpack-dev-server for alternative servers such as express or apache

After using vue-cli to scaffold a Vue app, I am looking to set up a new web server instead of webpack-dev-server. I am interested in having a separate configuration file to customize the server settings, similar to using Node Express for production deploym ...

When the Bootstrap carousel slides, enhance the navbar text with motion blur effects

One issue I'm facing is that when the bootstrap carousel changes the image, it adds the class "next" (transform: translate3d(100%, 0, 0); ) to the item and causes motion blur in my navbar menu text. https://i.sstatic.net/kRnb4.png You can check out a ...

Saving the state of checkboxes in Angular Material

I am trying to figure out a solution for storing checkbox values, specifically whether they have been checked before or not. For example, I have this dialog: https://i.sstatic.net/c16Ju.jpg After clicking on a checkbox and then clicking Save, the checkbox ...