JavaScript Loop Fails to Execute Entire Code Block

For some reason, I am encountering an issue with my function that involves a large for loop. When I print out the value of j inside the AJAX success call, it consistently shows as 6 (console.log(j) = 6 6 6 6 6 6). However, when I display console.log(j) before the success function, it displays the correct sequence of values from 0 to 5. Can anyone provide any insights into why this discrepancy is occurring or suggest what might be missing in my code?

function loadInfo() {
  var knuckles = "";
  for (var i = 1; i < channels.length; i++) {
    knuckles += "&login=" + channels[i];
  }
  $.ajax({
    url: url1 + channels[0] + knuckles,
    type: "GET",
    headers: {
      "Client-ID": "XXXXX"
    },
    success: function (json) {
      for (var j = 0; j < channels.length; j++) {
        console.log(j); // This logs the correct values
        $.ajax({
          url: url2 + json.data[j].login,
          type: "GET",
          headers: {
            "Client-ID": "aa20kjc6z0zwwogqpz3wqn3245qzc9"
          },
          success: function (json2) {
            console.log(j); // This logs incorrect values
            var sonic;
            if (json2.stream != null) {
              sonic =
                json2.stream.game +
                "</div>" +
                '<div class="info">' +
                "Apple" +
                "</div>";
            } else {
              sonic =
                '<span class="offlineText">Offline</span>' +
                "</div>" +
                '<div class="info">' +
                "Not currently streaming" +
                "</div>";
            }
            $("#streamerInfo").append(
              streamerBoxStart +
              '<div class="icon" style="background-image: url(' +
              json.data[j].profile_image_url +
              '); background-size: cover;">' +
              "</div>" +
              '<div class="nameGame">' +
              json.data[j].display_name +
              " ★ " +
              " " +
              sonic
            );
          }
        });
      }
    }
  });
}

I'm wondering if this could be related to variable scope, loop behavior, or perhaps something crucial that has escaped my attention. Please note that this segment is just one part of my overall code, with other components present above and below it.

Answer №1

Using the following sample as a guide: JavaScript closure inside loops – a simple yet practical illustration

Wrapping the j variable.

function fetchData() {
  $.ajax({
      success: function (data) {
      for (var j = 0; j < items.length; j++) {
        console.log(j); // This is where j contains the correct values
        (function(j) { // Insert this line
            $.ajax({
              success: function (data2) {
                console.log(j); // This is also where j retains the correct values
              }
           });
        )(j); // Insert this line
    }
  });
}

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

Initiate the function once the condition is satisfied (contains the class "in-view")

Here is the code for an animation: var setInter = null; function startAnimation() { var frames = document.getElementById("animation").children; var frameCount = frames.length; var i = 0; setInter = setInterval(function () { fr ...

Matching only digits in Javascript using Regex when they are not immediately preceded or followed by letters

Looking to find digits but not when they are part of words (using JavaScript). The examples that should yield a match: 1 1,2 1.5-4 (matches 1.5 & 4 separately) (1+3) (matches 1 & 3 separately) =1; The following examples should NOT produce a matc ...

send data to pop-up using POST method

I am facing an issue while trying to send a variable to print on a modal. I keep getting the error Notice: Undefined variable: ordID Despite searching through several sources, none of the solutions seem to work for my problem. This is my code: Table with ...

The attributes for CylinderGeometry in THREE.js are not specified

I've encountered an issue with accessing the .attributes.position for geometry in THREE.js. The console is returning an error message: 'Uncaught TypeError: Cannot read properties of undefined (reading 'position')'. const cylinderGe ...

Is the node certificate store limited to reading only from a predefined list of certificates?

Is there a way to add a new certificate to the list of certificates node trusts, even after some struggle? It appears that Node only trusts certificates hardcoded in its list located here: https://github.com/nodejs/node/blob/master/src/node_root_certs.h ...

"Encountering issues with the callback function not being returned in node

Currently, I am leveraging the node AMQP module to establish a connection with RabbitMQ. The process includes successfully connecting, setting up an exchange, queue, and sending messages to the exchange, which can be verified on the management console. Ho ...

Obtain the response body in Nest JS middleware

Currently, I am working on developing logging middleware for my project. My main goal is to log the response body specifically in 500 responses. However, I have encountered an issue where the response body is not present in the Response object when using a ...

Critical Issue: TypeError - The property 'interface' cannot be deconstructed from 'require(...)' because it is not defined

I am puzzled by the error I encounter when running 'npm run test' in the terminal. The error seems to originate from the file called lottery.test.js. Despite double-checking the syntax and ensuring that I exported the modules correctly from the c ...

Persist with displaying and concealing divs as we navigate through different pages

Incorporating a function into my main page has been successful so far, but I am seeking guidance on how to effectively utilize the function: localStorage.setItem("language", selectedLanguage); currentlanguage= localStorage.getItem("language"); My object ...

Use jQuery to target videos within a div and set them to mute

Looking for a way to mute videos using jquery when a certain button is clicked. This is the HTML code I'm working with: <button id="mute">Mute all</button> <button id="unmute">Unmute all</button> <div id="displayer">&l ...

The value of a variable undergoes a transformation following its insertion into an

During my coding tests, I came across this snippet of code: <script> var newData = {}, graphs = [] for(var j=0; j<2; j++){ newData["name"] = 'value '+ j console.log(newData["name"]); graphs.push(newData); console.log ...

Issue: Experiencing multiple re-renders when attempting to send a post request to the backend using

export default function CRouter() { const [token, setToken] = useLocalStorage('auth', '') const [user, setUser] = useState(false); const GetUser = () => { if (token !== "" && !user) { axios.post(&apo ...

Which delivers better performance: HTTP request from server or client?

Considering the optimal performance, is there a difference in using Angular's HTTP request within a MEAN-stack environment compared to utilizing Request.js or similar for server requests? ...

React will not trigger a re-render when modifying the state of an array of objects

I've encountered an issue where my table fails to rerender, even though the state update successfully modifies the array. However, the table does not reflect the changes. Initially, my state is set up as follows: const [data, setData] = React.useSt ...

Aligning Content in the Middle of a Bootstrap Column

Can anyone help me with centering the content of a bootstrap column vertically? I'm facing an issue when setting width: 100% and height: 100% for the overlay div. Any solutions? Here is an example image of what I am trying to achieve: https://i.ssta ...

Preventing the selection of 'None selected' upon dropdown change

When using the NameTextBox Dropdown, all names are available for selection. Upon changing a name and clicking on search, the associated details are retrieved. However, by default, 'None Selected' is displayed. Is there a way to prevent 'None ...

What could be causing the Babel installation to fail within Electron? Is Babel necessary for my project or can it be avoided?

Having trouble using the npm package https://www.npmjs.com/package/swipe-detect and encountering the following error message: export default function(target, callback, threshold=150) { ^^^^^^ SyntaxError: Unexpected token export at Module._compile (i ...

Determine the combined sum of two tables

I have set up two HTML tables that calculate totals per column. However, I'm facing a challenge: I am unsure how to get the grand total of both tables combined. My goal is for the table to dynamically update the totals as you input new numbers and p ...

instead of downloading the file, click on the provided download link to open it directly

Currently, I am utilizing Python Selenium to web scrape images in Chrome. To complete the download of these images, I generate download links using the subsequent code snippet: script_js = 'var imageURL = document.getElementsByTagName("{select_ta ...

Unexpected results occur when accessing data in $uibModal.open() within Angular JS causing it to

Here is the code snippet that is causing the issue of returning undefined items in AngularJS: App.js code console.log('single page application script is working'); var myApp = angular.module("demoApp", ["ngRoute", 'ui.bootstrap',&apos ...