Executing a for loop with a parameter passed into the setTimeout function

Help Needed with AJAX Request Timeout Issue

I recently created an array and tried to send an ajax request using setTimeout. However, I encountered a problem where I couldn't get the parameter in setTimeout. The console log showed that the variable 'i' was undefined. Can anyone guide me on how to resolve this issue?

Console Log Result:

i undefined

Javascript Code:

$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);
        $scope.params = {
            lat: $scope.lat,
            lng: $scope.lng,
            time: $scope.time,
            type: $scope.type[i]
        }
        console.log("params", $scope.params);
        return;
        $.ajax({
            type: 'post',
            url: "bz.php",
            dataType: 'json',
            async: true,
            cache: false,
            data: $scope.params,
            success: function (data) {
                if (data.response) {
                    console.log("data.response", data.response);
                    return;
                    if (!$scope.$$phase) $scope.$apply();
                } else if (data.response == null) {

                } else if (data.error) {

                }
            },
            error: function (data) {
            }
        });
    }.bind(this), i * 2000);
}

Answer №1

To encapsulate the value of i, pass it as the third argument in setTimeout:

setTimeout(function(i){ // <--  ... and access it inside this function
   console.log(i);
}, i * 2000, i);// <--- store the value of i here ...

Answer №2

Using .bind() is unnecessary in this case. You can opt to use either let or const rather than var...

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (let i = 0; i < $scope.type.length; i++) {
    setTimeout(function () {
        console.log("i", i);

        // your code

    }, i * 2000);
}

Alternatively, you could simply pass i as an extra argument to the setTimeout function.

const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];

for (var i = 0; i < $scope.type.length; i++) {
    setTimeout(function (i) {
        console.log("i", i);

        // your code

    }, i * 2000, 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

Having trouble pushing data to the mongo/express api endpoint

Struggling to insert data into my MongoDB database from my Angular 2 frontend. Despite using morgan to log all requests, nothing seems to be going through as I don't see any entries in the database. Here's my API route: // add venue router.post ...

Using HTML Select field to make ajax calls to web services

When working with modals that contain forms to create objects for database storage, there is a Select field included. This is the code snippet for the Select field: <div class="form-group" id=existingUser> <label>Username</label> < ...

When running `npm start`, if you encounter an error message that says `npm ERR`,

When attempting to run this JS project on my Mac using this JS project, I encountered an npm error after typing npm start: https://i.sstatic.net/o2UZj.png Despite searching various websites for a solution, I have already included these lines in my packag ...

Guide to correctly inserting an image into a webpage using JavaScript

Currently, I am working on a tutorial for creating a dynamic webpage. The objective is to display the time and an image that changes based on the current hour. However, the method used by the instructor to insert the image is unfamiliar to me, and despit ...

Unable to execute tests on angular example project

I recently cloned the Angular Material-Start project. According to the documentation: When I run npm run tests to start all my Karma unit tests, I encounter an error: npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\DevSoft\\Node ...

Tips for copying files depending on the environment using gulp

I have a folder containing files for different build environments such as production, stage, and test. For example: src/config.prod.js src/config.stage.js src/config.test.js My goal is to copy the config file based on the environment provided. I am usi ...

"Clicking on the dropdown menu fails to trigger it to open

The dropdown menu within the navbar fails to open when clicked. Here's a snippet of the HTML structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-wid ...

Convert PHP array into a 2D JavaScript array

I am currently tackling the task of passing two SQL fields through PHP to JavaScript. While I have researched extensively on creating multidimensional arrays in JavaScript, I find myself stuck when it comes to translating PHP code into JavaScript. Although ...

Encountering issues with Windows 8 PhoneGap FileTransfer when trying to transfer text files

I'm facing an issue while attempting to upload a file to a server - the process seems successful, but the file doesn't actually transfer. I've temporarily hard-coded some values, but here's the code snippet: var options = new FileUplo ...

What is the best way to launch a Popup window that spans from the top to the bottom of the screen?

I'm attempting to create a popup window that stretches from the top of the screen to the "applications" bar in Windows. Here's the code I'm using: function windowOpener(windowHeight, windowWidth, windowName, windowUri) { var windowHeight = ...

Sending a PUT request using AJAX with JSON payload to an ASP.NET Web API endpoint

When attempting to perform a simple AJAX PUT operation on my API method, I found that the parameters were not being set and remained as 0. This occurred despite the request reaching the API method without any errors. What could be causing this issue? AJAX ...

Using JavaScript to convert date and time into ISO format

Similar Question: How do I output an ISO-8601 formatted string in Javascript? I've been attempting to change a date and time input into an ISO format but keep encountering the error .toISOString is undefined. It seems like I must be overlooking s ...

Optimize your React application by eliminating debug code before deploying it to production

Currently, I am developing a React App within an npm environment. Throughout my JavaScript code, I have the following snippet in multiple JS files: ... let url = loc.protocol + "//" + loc.hostname + (loc.port ? ":" + loc.port : "") + "/" + baseUrl; if (D ...

Language Translation with Angular

Link to the Fiddle In angular-translate, is it possible to automatically pull a key-value pair from another language if it is not available in the current language? For example, if I have English and Spanish translations and a certain key-value pair ("CON ...

Ways to streamline data consolidation in AngularJS when dealing with multiple identical items

New to the world of Angular, I'm looking to combine items with the same names from an array. $scope.items_list = [{name: 'cars',quantity: 2}, {name: 'cars', quantity: 4}, {name: 'cars', quantity: 5},{name: 'truck ...

Tips for generating rows in an HTML table

I'm attempting to generate a table with 5 rows and 4 columns, displaying increasing multiples of a user-input number. While I can print the numbers successfully, they all appear in one column. I thought breaking up the loops would solve this issue, bu ...

HTMLElement addition assignment failing due to whitespace issues

My current challenge involves adding letters to a HTMLElement one by one, but I'm noticing that whitespace disappears in the process. Here's an example: let s = "f o o b a r"; let e = document.createElement('span'); for (let i ...

Tips for incorporating an if statement into embedded HTML using JavaScript in order to reveal a CSS class

How can I dynamically display different classes based on the presence of data in a JavaScript array? For example, if there is responseData.title, show the class 'grey'; otherwise, show the class 'white'. This is what I am attempting t ...

Addressing the issue of pm2 with netmask 1.0.6 posing a serious security risk

While working on my project, I encountered a problem in the terminal when using the pm2-runtime command for the runtime environment. When running the command npm i, I received warnings at two levels: High netmask npm package vulnerable to octa ...

Which programming languages are essential for creating a successful Electron application?

A few months ago, I embarked on the journey of delving into the world of Electron. Despite being a PHP developer, I have been immersing myself in resources online to learn about nodejs and express. Can anyone provide guidance on what specific areas I shou ...