I had a forEach()
loop set up that was running through a number of Docs from Firebase exactly the same as the exmaple code and it was working great… Until I found out Firestore stores docs lexicographically. Which ended up ruining my forEach() loops.
So I put the data from Firebase into an array like so…
const timeArray = [
vhfSnap.get('time1'),
vhfSnap.get('time2'),
vhfSnap.get('time3'),
vhfSnap.get('time4'),
vhfSnap.get('time5'),
vhfSnap.get('time6'),
]
I am now running the for each loop on the ‘timeArray’ array but now the forEach loops arenβt working properly for some reason. Ive gotten some instances of the forEach loops to work as there are multiple instances of them… But the ones Iβm having trouble with most are the ones that have setTimeouts()
in them.
The setTimeout()
functions are no longer waiting to be complete and just firing without waiting… They are also firing in an odd order.
This is the code Iβm running:
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++
};
});
Why did this code work perfectly with the Firebase data but now it doesnβt work with array data? What am I missing? I’ve tried for 2 hours and been through all the similar questions on here to try and figure this out, but have had no luck…
Edit:
I have just tried to replicate the results in a less complicated way:
const fruits = ['π', 'π', 'π']
fruits.forEach(fruit => {
function print() { console.log(fruit)};
setTimeout(print, 1000)
})
This also has the exact same issue. There is something going on with the setTimeout being used with data from an array..
2
Answers
Have you checked to see the values of
timeDataMs
? If that value is undefined (I think) or if whatever value you have for it cannot be converted into a number, the function reference will fire immediately.Try this
EDIT