Using a timeout does not solve your problem, it simply avoids it. Don’t settle for doing less than your best. Choosing to go an incorrect route instead of rewriting the code correctly may help you pass the challenge and save you time, but in the end, it will waste you more time than learning how to do it correctly now. I assume you are using freeCodeCamp to be able to learn how to program. Why not use an easy project like this to actually learn how to properly handle asynchronous code, instead of hampering your skills just to get by. Learn and understand how callbacks really work. Learn how Promises and Async Functions work. I don’t think rewriting less than 100 lines of code is that big of a pain in the butt. Don’t cheat yourself on learning.
Unfortunately, I can’t compare that for loop code to your previous, because you have now changed it to using the settimeout. If I remember correctly based on my previous answer, you had your ajax call in a for loop structured something like this pseudocode:
var users = []
for (user in users) {
$.ajax(user) {
// append data
}
}
they have it structured like this:
var users = []
$.ajax(users) {
callback(data) {
for (user in data) {
// append data
}
}
}
The difference is subtle, but it relies on a proper knowledge of callbacks. Read my first answer. I told you that you can’t do AJAX in for loops, and that your app looked like this:
for loop 1 => calls data for every user
for loop 2 => calls data
-- several milliseconds later --
<= data from for loop 1 is received and placed on page
<= data from for loop 2 is received and placed on page
If I was to draw up this other codepen app the same way, it would look like this:
AJAX request data => call callback function when done
callback function receives data
for loop 1 places data on page
for loop 2 places data on page
In their codepen, they run the for loop after they have received the data, therefore the if statement works. In your codepen, you were running the for loop before you got the data. In your set timeout code, you are using a callback:
setTimeout(yourCode, 3000)
and yourCode is “called back” after 3000 milliseconds. In their codepen, their code is called back after the data has been recieved. Again, the problem is not with your approach, it is with your current understanding of callback functions and asynchronous JavaScript. I can’t stress it enough, you really need to learn how to properly write asynchronous JavaScript, or you will just not get anywhere. You have nothing to lose by watching and reading the links I posted above, its free and you can do it in a couple hours. With just a little bit of study, I think you will be able to not just work around the issue, but actually understand what is going on.