Executing a JavaScript delay within a for loop using an array

Hello everyone, I need some help with a code snippet I'm working on. The code retrieves data from Google Sheets which includes addresses and amounts, then stores it in an array of arrays. I want the script to pause for 10 seconds between each iteration as it loops through the array. Here's what I have so far:

const randomArray = [];
for (var i = 0; i < rows.length; ++i) {
    let row = rows[i];
    randomArray.push(row);
}
for (const data of randomArray) {
    setTimeout(() => {
        const AddressID = data[0];
        const Amount = parseFloat(data[1]);
        console.log(AddressID, Amount);
    }, 10 * 1000); // Changed the timeout to 10 seconds
}

There are a total of 4 addresses and amounts that need to be processed one at a time with a 10-second interval between them. My current implementation only waits 5 seconds and then outputs all 4 address and amount pairs simultaneously.

Answer №1

  • Instead of using setInterval, opt for setTimeout
  • Iterate through the array and set intervals based on the index to ensure proper execution timing for each callback (e.g., use i * 10000 instead of 5 * 1000 for delay, where i represents the current index)
  • Utilize Array#map over a traditional for-loop to avoid issues with the index variable losing its value once callbacks are executed

Example

let randomArray = [[1,10], [2,20], [3,30], [4,40]];

randomArray.map((el,i) => {
  setTimeout(() => {
    const AddressID = el[0];
    const Amount = parseFloat(el[1]);
    console.log(AddressID, Amount);
  }, i * 10000);
});


Another approach is to create a recursive function that generates a new timeout each time the previous callback is executed until all elements in the array have been processed

Example

let randomArray = [[1,10], [2,20], [3,30], [4,40]],
    i = 0;
    
(function loop() {
  setTimeout(() => {
    const AddressID = randomArray[i][0];
    const Amount = parseFloat(randomArray[i][1]);
    console.log(AddressID, Amount);
    i++;
    if(i < randomArray.length)
      loop();
  }, i * 10000);
})();

Answer №2

To ensure you obtain the index of an array, it is essential to utilize a standard for loop rather than using the of iteration:

const randomArray = [];
  for (var i = 0; i < rows.length; ++i) {
    let row = rows[i];
    randomArray.push(row);
  }
 for (var j = 0; j < randomArray.length; j++) {
        var data = [randomArray[j]];
    setTimeOut(() => { console.log("Delay")}, j * 5000);
    const AddressID = data[0];
    const Amount = parseFloat(data[1]);
    console.log(AddressID, Amount);
    }

This function will execute every five seconds; feel free to adjust the time interval by modifying the value from 5000 to your preference.

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

Combining two objects in Typescript using the spread operator and creating a reusable type

Is there a more streamlined way to dynamically add a question mark to a variable type in TypeScript, or is the approach of rewriting the type with a question mark the best way to achieve this? I'm looking to ensure that the original variables remain r ...

What is the best way to retrieve a comprehensive outcome from a sql search utilizing php and consequently showcase it using javascript?

Need help with my PHP script that executes a query and returns multiple rows? Learn how to use json_encode in conjunction with JavaScript to fetch this data and display it in a table. This code snippet echoes two JSON encoded lines, each representing one ...

issue with customized select dropdown within a bootstrap modal window

Exploring how to implement a customized select box with unique CSS and search functionality within a Bootstrap modal. Here is the code snippet for the select element: <link rel="stylesheet" href="chosen.css"> <select data-placeholder="Choose ...

It is not possible to alter the req.ip in the Express framework

I am trying to update the value of req.ip using the express framework in node.js, but despite my efforts, req.ip remains unchanged. Strangely, when I set a custom member like req.my_var, it works perfectly fine. I'm puzzled by this discrepancy... Any ...

The jQuery load() method may not load all elements

I've been struggling with a query issue for quite some time now. I have a Content Management System that I want to integrate into my website, but unfortunately, I am unable to use PHP includes. As an alternative, I decided to utilize jQuery instead. D ...

Transformation of HTML occurs in React components upon saving in Visual Studio Code

As I embarked on my journey to learn React, I hit a roadblock early on. Searching for a particular setting, I somehow ended up selecting something different, like NodeJS. Now, the issue at hand is: Behold the First Image: https://i.sstatic.net/ETmDk.png ...

Click on the hyperlinks one by one that trigger ajax events

There is a feature on the popular social media platform reddit.com where you can load more comments by clicking a link. I understand that comments may be hidden for performance reasons, but I would like to automatically expand all comments without having t ...

What is the best way to retrieve a user's country name using C#?

Currently, my code utilizes geolocation to retrieve the user's country name. Take a look at the code snippet below: navigator.geolocation.getCurrentPosition(function (pos) { var latlng = pos.coords.latitude + "," + pos.coords.longitude; var a ...

Updating values of objects during iterations and for get requests is ineffective

Currently, I am looping through multiple select fields and attempting to run a get request for each of them. var selects = { key1 : value } $(".chosen-select-field").each( function ( index ) { selects[key2] = $( this ).attr('data-placeholder& ...

Comparing event.target with a selector can be easily done by utilizing Javascript methods

Within my function, I am assigning an onclick event to every node of a specific type in the document, based on the given node parameter. After that, I aim to target the element that was clicked and "bubble up" by applying an effect to the parent node sele ...

Conditionally remove elements from an array with multiple dimensions

I am faced with the following array structure: ["balance"]=> array(5) { [0]=> array(3) { ["balance"]=> string(4) "0.00" ["id_item"]=> string(3) "540" ["item"]=> string(7) "Lampada" } [1] ...

JavaScript function having an undefined value caused by a radio button

I am having trouble passing the value of a radio button to a JavaScript function. I have been testing my code but keep running into an issue where the returned value is always undefined. Here is the snippet of my code: <!DOCTYPE html PUBLIC "-//W3C// ...

Tips for producing/reserving cropped images from a photo? (includes converting images to base64 format)

https://i.sstatic.net/6Nath.png Imagine having two square datasets taggedImages: { 0: {id:0, left:100, top:100, thumbSize:100, type: 'A', seasons: ['All', 'All']}, 1: {id:1, left:200, top:200, thumbSize:100, type: &apos ...

Tips for discovering the smallest value within an array by utilizing the ternary operator in Swift

let items = [2,3,5,7,3,1,8,9,0,2,4,1] var minValue = items[0] for item in items { item < minValue ? minValue = item : minValue } print(minValue) I attempted this code, aiming to find the minimum value in the array. While I can achieve it using if..el ...

Every time ComponentDidMount is triggered, my component state automatically switches to "loading" in enzyme, which is not the behavior I

Within my component, I utilize the componentDidMount lifecycle method to set the state variable get_data_loader to true. async componentDidMount() { let writeAccess = (this.props.viewAsOriginalUser ? this.props.viewAsOriginalUser : isWriteable(th ...

Tips for submitting a form and retrieving session count without the need to refresh the page after submitting the form

I have set up a form that includes hidden input fields to send data to a PHP script. The script stores the values in an array of sessions by using AJAX to reload the page. Once the data is submitted successfully, an HTML alert message is displayed in <p ...

Does a Function Component become an object instance of itself when rendered with a tag?

Suppose I declare a constant variable num = 1 inside a function component. Would it be possible for me to reference this variable in the return statement as this.num? Is it permissible for function components to contain static variables of that nature? ...

Pros and Cons of Using HTML5 Mode versus Hash Mode in AngularJS

When using AngularJS 1.3, it is necessary to include the <base> tag in HTML5 mode. This led me to consider the pros and cons of HTML5 mode versus Hash mode. In Hash mode, the major drawback is that URLs can appear unattractive and may not be easy fo ...

Retrieve the JSON file only upon the first input change

On my backend, I have a JSON file containing suggested words for autocomplete in the search field. To improve performance, I don't want the JSON to load every time the page loads; instead, I only want it to load when someone wants to use the search f ...

Issue accessing string array passed as prop with numerical index in ReactJS and Typescript

As a newcomer to Typescript, I have quickly fallen in love with it. However, I am currently facing an unusual issue: I have created a string array in the parent component, passed it down to a child component as a prop, and attempted to access the array us ...