Repeatedly encountering identical values in delayed for loop

I can't figure out why my delayed for loop is consistently giving me a "-1" as the result.

for (var i = 5; i > 0; i--) {
    setTimeout(function() {
        console.log(i)
    }, i * 1000)
}

(I adjusted my variable to be 5)

Answer №1

To simplify the process, you can call a function within the for loop and have that function manage the setTimeout

for (var i = 5; i > 0; i--) {
  setCustomTimeout(i);
}     
        
function setCustomTimeout(i) {
 setTimeout(function() { console.log(i); }, 1000 * i);
}

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

Error in Angular Due to Circular Reference in JSON

I'm currently working on integrating a tree structure in AngularJS. The goal is to construct the tree by dynamically adding nodes based on user input from an Angular Select element. Here is the specific operation I'm trying to accomplish: var a ...

Loop through the array and eliminate the identification solely

{ "productGroupVariantss": [ { "id": 1378, "name": "No oF Poles", "variantsAttributeses": [ { "id": 391, "variantsId": null, "variantsValue": "1p" }, { "id": 392, ...

Experiencing an "Unsupported media type-415" error when making an ajax call using Jquery and ajax technology

When I try to update a specific record using an ajax function, I keep receiving a 415-Unsupported Media type error. Below is the JavaScript code I am using: $("#update").on("click", function(){ event.preventDefault(); return $.ajax('/upda ...

Performing a MySQL query to select multiple rows and fields with the AND operator simultaneously

I've got a table: + --------------------------+---------------------------+--------------+--------+ | ID | SKU_ID | DKEY | DVAL | + --------------------------+---------------------------+----------- ...

Is it possible to incorporate a combination of es5 and es2015 features in an AngularJS application?

In my workplace, we have a large AngularJS application written in ES5 that is scheduled for migration soon. Rather than jumping straight to a new JS framework like Angular 2+ or React, I am considering taking the first step by migrating the current app to ...

Click on a button to initiate the download of a collection of images

In my simple HTML structure, there is a button designed for downloading purposes: <div id="getImageWrapper"> <div class="image"> <p class="image-name">{{imageName}}</p> <button class="download-btn" @click="ge ...

What is the best way to access and display the innerText of elements that have been removed using console

When I call the updateCartTotal() function, my goal is to display in the console the items that have been removed from the shopping cart. Every time I click on the remove button, I want it to show the item and the price. However, instead of displaying the ...

Alert: Route.get() is requesting a callback function, but is receiving an [object Undefined] while attempting multiple exports

I'm attempting to export the middleware function so that it can be called by other classes. I tried searching on Google, but couldn't find a solution that worked for my situation. Below is the code snippet: auth.js isLoggedIn = (req, res, nex ...

Tips to successfully save and retrieve a state from storage

I've encountered a challenge while working on my Angular 14 and Ionic 6 app. I want to implement a "Welcome" screen that only appears the first time a user opens the app, and never again after that. I'm struggling to figure out how to save the s ...

Learning the process of accessing a JSON file from a different directory

I am faced with a straightforward folder structure, it looks like this: project │ └───data │ file.json │ └───js test.js My goal is to access the content of file.json within the test.js file in order to perform some ...

Error message received from GitHub when attempting to create a repository through the REST API states that JSON cannot

I am currently in the process of learning how to use REST APIs for GitHub, and my current project involves creating a new repository using JavaScript. Below is the function I have written for this purpose, which includes generating a token and granting all ...

Prevent the default cursor behavior in a textarea when keys are pressed with this simple guide

Here is some code I'm working with: textarea#main-text-area( rows="1" ref="textArea" maxlength="4096" v-model="message" :placeholder="placeholder" @keyu ...

Inquiry about JavaScript Arrow Function syntax issue

At the outset, I apologize for the vague title. It's challenging to explain without a direct demonstration. As a newcomer to JavaScript, I've been diving into arrow functions. However, there's a syntax of arrow function that I'm unfamil ...

Establish the Central European Time (CET) timezone using the toISOString

Has anyone figured out how to convert a MYSQL timestamp date to a JS date using toISOString() and adjusting the time-zone to CET? I have been trying to achieve this with the following code, which currently produces the format "2021-02-251 15:27:20" - howev ...

Tips for resetting the lightgallery following an ajax request

I have integrated the lightgallery plugin into my website to showcase images when clicked. The initialization of the light gallery is done like this: $(document).ready(function(){ $('#lightgallery').lightGallery({ selector: '.it ...

Is it possible to find out which JavaScript file the AJAX function is using to send a request to a Java servlet?

I am facing an issue with two js files, one.js and two.js. Both of these files make ajax requests to the same Java servlet class(AppController.java). Here is the code from one.js: function addOne(){ var formData = $('#form1').serialize(); ...

Extract the content of an element and incorporate it into a script (AddThis)

HTML: <div id="file-section"> <div class="middle"> <p class="description"> Lorem ipsum... </p> </div> </div> jQuery: var share_on_addthis = { description: $('#file-section ...

Effortlessly zoom the camera onto the object's position with a click of the mouse

Within my scene, I have several boxes and a PerspectiveCamera. My goal is to create a specific effect that triggers when I click on one of the boxes: The camera smoothly transitions from its current position to focus on the selected box The selected box ...

What is the best way to enable a visible bootstrap tab to be clicked more than once?

Is there a way to override the default behavior on bootstrap tabs that prevents clicking on the currently shown tab? I need the user to be able to click on the tab again even if it is already active, as I am using AJAX to load content and reloading the pag ...

Breaking down CSV rows and transforming numerical data (Typescript, Javascript)

Looking to convert a row from a csv file into an array and then transform the numeric values from string format. This represents my csv file row: const row = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323"; My objective is to create this array (with the ...