"Troubleshooting: Issues with Using setTimeout in a For Each Loop with an

I had implemented a forEach() loop that was iterating through a series of Docs from Firebase, following the example code, and everything was functioning perfectly... Until I discovered that Firestore organizes docs lexicographically, causing my forEach() loops to break. To counter this issue, I decided to store the data retrieved from Firebase in an array like so...

const timeArray = [
vhfSnap.get('time1'),
vhfSnap.get('time2'),
vhfSnap.get('time3'),
vhfSnap.get('time4'),
vhfSnap.get('time5'),
vhfSnap.get('time6'),
]

Now, when running the forEach loop on the 'timeArray' array, I am encountering problems with the functionality. While I have managed to get some instances of the forEach loops to work, those containing setTimeouts() are proving to be particularly troublesome.

The setTimeout() functions no longer adhere to the delay set and just execute without pausing as expected. Additionally, they appear to be firing in an unpredictable order.

Here is the code snippet I am currently using:

    var liCounter = 1;
timeArray.forEach((time) => {
    if (time != undefined) {
        let timeData = time;
        let timeDataMs = (timeData * 1000);
        let selectedTopic = document.getElementById('topic' + liCounter);
        function test() {
            selectedTopic.style.color = 'green'
        }
        setTimeout(test, timeDataMs)
        liCounter++

    };
});

I cannot understand why this code previously worked flawlessly with Firebase data but now struggles with array data. What aspect am I overlooking? Despite investing two hours into troubleshooting and exploring similar queries, I have yet to determine a solution...

Edit: I have attempted to simplify the scenario to replicate the issues:

                const fruits = ['🍎', '🍋', '🍌']
            fruits.forEach(fruit => {
                function print() { console.log(fruit)};
                setTimeout(print, 1000)
            })

This approach also encounters the same problem. It appears that there is a discrepancy arising when setTimeout is utilized in conjunction with data extracted from an array..

Answer №1

Before proceeding, have you taken a look at the content in timeDataMs? If this content is either undefined or unable to be converted into a numerical value, it may cause the function reference to trigger prematurely.

Answer №2

Give this a try

    let counter = 1;
    timeArray.forEach((time) => {
    if (time != undefined) {
        let data = time;
        let dataMs = (data * 1000);
        let chosenItem = document.getElementById('topic' + counter);
        function adjustColor() {
            chosenItem.style.color = 'green'
        }
        setTimeout(function() {
          adjustColor();
        }, dataMs)
        counter++

    };
});

UPDATE

function displayFood(food) {
  console.log(food);
}

function delayDisplay(food, duration) {
  setTimeout(function() {
  displayFood(food)
  }, duration);
}

const foodItems = ['🍎', '🍋', '🍌']
var index = 1;
foodItems.forEach(item => {
  var secondsDelay = index * 1000;
  delayDisplay(item, secondsDelay);
  index++;
});

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

Making a POST request to the API using a local server address

When using my localhost address to send an image to an API, the image is not being identified. However, it works fine when I use links from Google. The code I'm using is as follows: unirest.post(requestString) .header("X-RapidAPI-Key", API_KEY) ...

Tips for loading angularjs script files

In my AngularJS application, I have various controllers, services, and directives spread across multiple JavaScript files. While in reality there are more than just three of them, let's consider them as controller.js, service.js, and directive.js. To ...

What is the correct way to have Material-UI's <TextField/> component return with a ref attribute, similar to <input/> in ReactJS?

Using this particular method: handleClick(event) { const inputText = this.refs.inputText console.log(inputText.value.trim()) } I am attempting to make Material-UI's <TextField/> return the input text accurately with a ref, similar ...

Array class returned

Hello! I have a question regarding returning an array in Java. Specifically, I would like to know how to implement the get and set methods for this task. TypeOfWater[] waters = fetchTypes(); public String[] getTypeOfWater() { return waters;//How can ...

Attempting to transform a callback-dependent function into one compatible with generators (using yield) proves to be unsuccessful

Trying to synchronously invoke a regular call-back style function in koa using generators. This method has been successful: var output = yield function (cb) { myDaoObject.load(function (err, res) { cb(err, res); }) }; Now, attempting t ...

Error encountered when attempting to access a double-pointer array: Segmentation Fault/ Memory Access Violation

I have written a code snippet that demonstrates memory allocation for a dynamic array and the process of printing its values using a function called fn(). Due to specific requirements, I can only pass the array as int **v, rather than the usual method of ...

Combining multiple arrays in PHP to create a unique merged array

I have been developing a unique tool that merges arrays containing attributes together. However, I am facing a challenge in achieving this goal. My approach begins with decoding JSON data into arrays using the following code: $input = '{"1" ...

Vue.js encountered an unexpected strict mode reserved word error that was not caught

I have initialized a Vue instance var app = new Vue( {...} ) Additionally, I have defined a class named CustomTooltip class CustomTooltip { constructor(array_data,vue_instance) { this.tooltip_data = array_data; this.vue_instance = vue ...

NodeJS's pending ajax post using SailsJS

I'm experiencing an issue with processing AJAX data in my sailsJS app. The ajax post data always stays in the pending state, here is the code from my view: <script type="text/javascript"> $('#submit').click(function(){ $.ajax ...

Implementing OutlinePass from Three.js in React

I am attempting to implement the Post-processing Outline Thee.js example in a React environment with server-side rendering. The challenge I am facing revolves around lines 47 and 280 in the example: <script src="js/postprocessing/OutlinePass.js">< ...

Create a constant variable to store the value retrieved from the request.get method in Node.js, which can be

In my project, I have a utils layer that contains various functions, such as getUserInfo(userToken), which is used to retrieve the userId. Since Node.js works asynchronously, I am looking for a way to achieve certain functionality without using callbacks a ...

Deciphering a JSON response obtained from a jQuery output within a PHP context

I have created a simple search form that uses jQuery to query an external server for results. $("#formsearch").on("submit", function (event) { // all good! event.preventDefault(); submitFormSearch(); }); function submitFormSearch() ...

Encountering an "invalid query parameter" error when making a find request with FeatherJS and ReactJS

Adding $show:true to the data below results in an error when making the find request. However, when I remove $show:true, everything works perfectly with no errors. The error message states: Invalid query parameter $show. I have attempted using differe ...

JavaScript: Dynamic animation of a DIV element based on conditions

I am looking to create an animation for a DIV layer when another div is clicked. However, I only want the animation to play if the DIV layer has not been animated yet. My initial thought was to check the height value, as I am animating the height of the d ...

Attempting to convert PHP tables into PDF format by utilizing jsPDF-auto-table to generate a beautifully structured PDF file containing the results of a PHP query with multiple records

I'm new to stackoverflow but I find myself visiting it regularly for helpful tips. I've taken some code from the simple.html file that comes with the jsPDF auto-table plugin. However, I'm having trouble making it work with data generated by ...

Showing a 2D array in Jquery within an MVC environment - what's the solution?

I am in the process of building an MVC application. My goal is to transmit data from the controller and display it using JQuery. I have constructed an array in the controller and sent it to JQuery using Json. Here is the array... And here is the JQuery ...

How can we use an Array containing nested Objects in TypeScript?

Wondering about the best way to achieve this: let x = [{}]; in TypeScript. I've searched high and low for a definitive answer to this query. My assumption is that it can be done using the Array object: let x : Array<Object> = new Array<Obj ...

What is the best way to execute obj.foo() and obj(a).foo together? (inspired by jQuery)

Apologies for my less than perfect English. I am working on improving it and will do my best. I'm exploring something new in javascript that was inspired by the jQuery library. There are two different ways to use 'jQuery' or '$'. ...

Properly defining a DI service in Angular 2.1.2 using ES5

I have created an Angular 2 service that utilizes the Http service and is accessed by other components. However, I am unsure if my implementation is correct: (function (app) { 'use strict'; app.LoaderService = ng.core.Component({ providers: ...

Comparing a 1D Array to a 2D Array in Java: Methods and Strategies

I am struggling to compare a 1D array with a 2D array. I have imported the txt file into both a 1D array and a 2D array. The 1D array contains 20 correct answers (True and False). The 2D array consists of 2000 student answers (100 students * 20 answers per ...