The for loop does not pause until the ajax response is received

When I enter the for loop, an ajax call is made. However, the for loop does not wait for the ajax call to receive a response before incrementing the value, causing the response to update to the wrong div element.

For example: Let's say we have 'N' number of divs with ids divid0, divid1, divid2, divid3, divid4........ dividn.
In the loop (for(var i=0; i < n; i++)), when 'i' is initially zero, I intend to update my first ajax response to the div with id "divid0". But because 'i' increments to one before the ajax response is received, the data meant for "divid0" ends up in "divid1" instead.

I initially tried solving this issue using synchronous ajax calls. However, this caused another problem where users were unable to scroll down the page until the entire content was loaded. With around 10 sliders on the page, it took over a minute to fully load and become visible to the user. As a result, I want users to be able to scroll down the page even while it is loading (after at least one slider is loaded).

Thank you in advance. Below is the code snippet:

for(var sliderId=0; sliderId < 6; sliderId++){ 
    $.get('api url', {}, function(response){
        if(!response){ 
            $("#slider"+sliderId).html('Currently there are no items in this category');
        } else{
            if((response.results) && (response.results.length > 0)){
                getInfo(response, sliderId);
            }        
        }                
    });     
}

Answer №1

One approach to achieve the desired outcome is by implementing a recursive method.

 var sliderId = 0;
function retrieveData(sliderId)
{
  $.get('api url', {}, function(response){
    if(!response){ 
        $("#slider"+sliderId).html('Currently there is no items in this category');
    } else{
        if((response.results) && (response.results.length > 0)){
            processInfo(response, sliderId);

        }        
    }  
    if(sliderId < 6)
               retrieveData(sliderId++)              
});     
}
retrieveData(0)

Answer №2

The issue at hand is that the 'sliderId' variable used in all responses is referencing the same value. Since the callback function is not executed until after the for-loop completes, each response call will have 'sliderId' set to 6. A solution to this problem is to create a new scope for each ajax call, as MMK suggested.

One way to do this could be:

for(var sliderId=0; sliderId < 6; sliderId++) {
 updateDiv(sliderId);
}

function updateDiv(sid) {
  $.get('api url', {}, function(response){
    if(!response){ 
        $("#slider"+sid).html('Currently there is no items in this category');
    } else{
        if((response.results) && (response.results.length > 0)){
            getInfo(response, sid);
        }        
    }                
  }); 
}

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

Using LocalStorage in Greasemonkey

I am currently working on developing a Greasemonkey script, but I am encountering difficulties with implementing local storage within it. The method I found to work with local storage in Greasemonkey involves creating another instance of JavaScript using t ...

Is there a way to monitor the home button press event within a PhoneGap application?

Hello! I'm curious if there is a way to track when the Home button is pressed on both Android and IOS using phonegap phonegap build. I have looked into events for the home button press, but have only found information on back button events so far. ...

Guide on how to navigate back to the login page when the access_token in local storage is not defined

Whenever my localStorage turns undefined, I need to redirect the user to the login page. However, this is not working as expected and I'm not sure what the issue is. Below is the code from my PrivateRoute.js: PrivateRoute.js import React from " ...

How can I extract several values from a child component in React?

Is there a way to retrieve two values in a single method of the Parent Component by passing props value from Child Component? What would be the best approach? Form.js (Child Component) // First method -> Extracting the suggestion value and passing i ...

Ensuring the vue carousel component stops rendering once all of its data has been displayed

Is it possible to stop rendering a vue carousel component once its data is displayed or after a certain amount of time? I've searched for information on this, but haven't found anything relevant. Despite it being an unusual request, I still want ...

Would you like to learn how to set an auto-play video as the background in a webpage section, similar to the one found on http://www8.hp.com/in/en/home.html?

I was browsing the HP-India website and noticed they have a cool autoplay video in the background of a section below the header. I would love to recreate something similar on my own website. Any tips on how to achieve this? ...

Retrieve JSON data from an object using the Amplify Storage feature

I recently retrieved data from an object in an S3 Bucket using Amplify. export function amplify() { let key = "68a92d44-f25a-4bd8-9543-cc95369ae9a0"; return Storage.get(key + ".json", { download: true }) .then(function(result) { return ...

Best Practices for Implementing Redux Prop Types in Typescript React Components to Eliminate TypeScript Warnings

Suppose you have a React component: interface Chat { someId: string; } export const Chat = (props: Chat) => {} and someId is defined in your mapStateToProps: function mapStateToProps(state: State) { return { someId: state.someId || '' ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

Display a table using Angular's md-card and md-color

Hey there! I'm currently working on printing a table that is filled with data in an md-card. The background color is set using the md-color theme picker, which you can check out here. However, I'm encountering an issue where the printed table onl ...

What causes the lack of impact on lambda rendering speed despite integrating webpack?

Hey there, I've been working on implementing webpack for a project that involves microservices, Node.js, TypeScript, AWS, and AWS SAM. My main objectives are: Reduce the cold start time of lambda functions. Minimize security vulnerabilities by e ...

What is the reason behind observing numerous post requests in the Firebug console after submitting a form through Ajax in jQuery?

I have integrated the jquery Form plugin for form submission and everything seems to be functioning properly. However, upon turning on the firebug console and clicking the submit button, I notice that there are 10 post requests being sent with the same da ...

Converting an Observable Array into a nested JSON structure

Having difficulty storing an array of information properly as JSON. A visual representation of the issue can be seen in this fiddle. Input a set of tags and check the console for output. Additional detail: An input captures a comma-separated list of tag ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

The functionality of the Ajax code is taking an unusually long time

After running my Ajax code, it took a surprising 3 minutes and 15 seconds to load. What could be causing this delay? <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.j ...

Stellar for occasions that don't come around often

Is it worth utilizing a Comet for events that do not require real-time updates, but can have a delay of around 1 minute? Examples could include: updates on Twitter statuses notifications on Facebook While Comet is commonly used in chat applications (suc ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

Clicking on the button has no effect whatsoever

I'm currently dealing with a button on my webpage that seems to be causing me some trouble: <script> function changeMap() { container.setMap(oMap); } </script> <button onClick="changeMap"> Click here </button> Upon inspe ...

Issue with custom fonts not showing in PDFs when using Puppeteer, even though they are displayed in screenshots

I've been working on dynamically creating PDF files using the puppeteer library, but I'm facing an issue where the generated PDF doesn't display the custom fonts (.woff) that I have specified. Instead, it defaults to using the system font, T ...

Constructing Browserify with dependencies containing require statements within a try-catch block

When attempting to integrate timbre.js (npm version) with Browserify, I encountered an issue where require statements for optional dependencies were enclosed in a try statement (check the source here). This resulted in a browserify build error displaying: ...