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..