What is the reason for the unusual incrementing of the index in JavaScript?

When running this code snippet, the first console log correctly shows 0. However, the second console log displays 1. Why is the index being incremented before the loop has ended?

for (var i = 0; i < this.offlineTimeSlots.length; i++) {

          console.log(i);

          this.http.post('http://localhost:63203/api', JSON.stringify(this.offlineTimeSlots[i]), { headers: headers })
            .map(res => res.json())
            .subscribe(data => { 

              console.log(i);

              resolve(data);
            }, (err) => {
              reject(err);
            });
        }

Answer №1

Performing an operation inside a for loop like this results in generating this.offlineTimeSlots.length HTTP requests (async). Typically, the for loop will complete its iterations almost every time before the async requests are made.

Consider the following example:

for(var i = 0; i < 10; i++){
    console.log(i);
    setTimeout(()=>{
        console.log(i);
    },2000);
}

This code will display numbers from 0 to 9 and then print 10 ten times. This happens because 10 async requests are created within the loop's length. The for loop finishes iterating faster than 2 seconds, causing the i value to be 9 + 1 (due to post increment) when the setTimeout functions start executing.

Source fiddle: https://jsfiddle.net/echonax/c9p4e19o/

Answer №2

this.http.post is an asynchronous function, meaning it will be executed separately from the rest of the code.

The for loop will continue running regardless of the status of this.http.post.

This concept operates using an event-loop mechanism: Learn more by reading this informative article - Click here to dive in!

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

What is the best way to integrate urql data into React similar to redux?

Currently, I am utilizing urql for making GraphQL API calls in one of our projects. In projects where we are working with RESTful APIs, I typically rely on redux to manage re-renders whenever there are changes in the data. Given my limited experience with ...

Error in template loading

Currently, I am going through the Angular.js tutorial to learn how to incorporate some of its advanced features into my existing applications. Everything has been smooth sailing until I reached the (angular route) section. Unfortunately, I've hit a ro ...

Can someone explain why the index call is not reaching the "/" route in Node.js?

When I access the server by going to http://localhost:3000, it displays my index file but does not route to the get function in index.js. I am currently stuck at this point. Below is my app.js file: var express = require('express'); var path = ...

The iPhone webview keyboard causes the layout to be pushed upward and remain elevated

While editing text fields, the native keyboard pops up and stays visible in the webview. It's almost like leaving the toilet seat up! Is there a way to return to the original scroll position after the native keyboard disappears? Perhaps an event that ...

Adding a class to a clicked button in Vue.js

A unique function of the code below is showcasing various products by brand. When a user clicks on a brand's button, it will display the corresponding products. This feature works seamlessly; however, I have implemented a filter on the brands' lo ...

Stretching a row in Wordpress Visual Composer and setting the direction to Right-to-Left

Whenever I attempt to expand a row using the row settings in Visual Composer, the row stretches but the alignment of the row becomes completely off. This issue only occurs when the body direction is set to direction:rtl in the CSS. You can view the websit ...

What is causing the "else" to activate in this particular if-else scenario?

I have implemented a method in Vue that toggles the darkMode variable when clicked. However, I'm facing an issue where it always triggers both the if and else parts of the method. data(){ return{ darkMode:false, } }, methods:{ darkMode ...

Error: Invalid hook calls detected in React using Material-UI components

Hey there! I'm relatively new to the world of React and I've been tackling an issue with implementing the SimpleBottomNavigation component. Unfortunately, I keep running into an error message that says: "Uncaught Error: Invalid hook call. Ho ...

Learning to monitor for incoming messages in a Discord channel from the ground up

I am eager to understand how to detect new messages exclusively using requests made to the Discord API. While I have mastered loading messages by fetching , I am struggling to grasp how to listen for incoming messages. It appears that this feature is not ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

PHP-generated HTML onclick attribute malfunctioning

Here is the PHP code I am currently working with: $listing .= "<button onclick='updateValue(".$id.", ".$key.")'>change value</button>"; The variable $id is an integer and functions correctly. However, $key is a reference from a for ...

Using the p-multiSelect component in Primeng for Angular 2

Within the user.component.html template, I am utilizing a Primeng component. <p-multiSelect name="roles_id" [(ngModel)]="selectedRoles" [options]="user.roles"></p-multiSelect> When loading the input data, how can ...

Exploring the resolution of unit test for an Angular Bootstrap modal using the John Papa ViewModel style

A custom ModalService has been created to display two different types of dialogs, CancelDialog and ErrorDialog, based on the parameter passed to the service. For example, the following code will show an ErrorDialog: ModalService.openModal('Analysis ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

Verifying Dates with Bootstrap DatePicker

My bootstrap datepicker has a startDate value of '1/1/1990', but when a user manually enters a date like '1/1/201' (possibly a typo for '1/1/2014'), the date field becomes blank when they move to a different section. Is there ...

Options for line colors in three.js

Here is the code I currently have: const materialLinearInterpolation = new THREE.LineBasicMaterial({ color: 0x0000c9, linewidth: 1 }) const pointsLinearInterpolation = [] for (var i = 0; i < this.pointsCoordinatesLinearInterpolation.length; i++) { ...

angular pipe and tap methods fail to execute the designated function

I am encountering a problem when calling a function in my login service. I have tried using a pipe and tap. Interestingly, when I use res => console.log(res), it outputs the desired result. However, when I attempt to call a function, it seems that the ...

How can I turn off automatic ellipsis on my IOS device?

Currently, I am working on a web application that involves displaying location descriptions retrieved from an API. The issue I am encountering is that the description is being cut off with an ellipsis after a certain number of lines when viewed on an iPhon ...

Access Select without needing to click on the child component

I am curious to learn how to open a Select from blueprint without relying on the click method of the child component used for rendering the select. <UserSelect items={allUsers} popoverProps={{ minimal: false }} noResults={<MenuItem disabled={ ...

Tips for updating the display after making an angular $http request using rxjs Observables

I have a project where I am utilizing angular's $http service to fetch data from a remote endpoint. I am keen on incorporating rxjs Observables, hence the call in my service is structured as follows: userInfo() : Rx.Observable<IUserInfo> { ...