Pedro Heck
Pedro Heck

Reputation: 69

Update HTML text content in a while loop

I'm having a problem that seems very simple, but still I don't know how to solve it.

So, I have this tag in my HTML file:

<p id="best-individual-text" style="display: inline-block"></p>

For context, I'm building a simple genetic algorithm to evolve a population of individuals (strings) in order to reach a target phrase. In my .js file, I have a loop that creates the new population and finds the best individual of that population, and the loop only stops when one of the individuals is identical to the target phrase.

What I want to do is to update the best-individual-text text content with the string of the best individual in each generation. Since the while loop creates a new population in each iteration, there's going to be a new best individual at every iteration.

Inside this while loop, I have the following line of code:

    document.getElementById("best-individual-text").textContent = getBestIndividual();

Note: getBestIndividual() returns a string

And here lies my problem: the HTML doesn't get updated. The tag remains blank until the loop stops, and only after that the tag is filled with the last best individual.

It works fine if I try this manually, that is, outside of the while loop. My only guess is that the while loop runs too fast for the HTML to be updated. Still, I think I've seen people update the HTML in a while loop, so I really don't understand the reason it is now working.

Also, I've tried making a setInterval instead of a while loop, but it still doesn't work. Even if it did work, it is not of my interest to have any sort of interval for each loop.

What could the problem be, and how can it be fixed?

Thank you in advance!

Here's the github in case anyone needs to see more of the code: https://github.com/pedroheck/genetic-algorithms/tree/main/Word%20Race

Upvotes: 0

Views: 808

Answers (1)

Andrew Stegmaier
Andrew Stegmaier

Reputation: 3787

I tried out your code, and in the cases I hit where you enter some text, click "Submit", and nothing happens, what is actually happening is that your algorithm is in some sort of infinite, or long-running loop, and it never hits the point where you try to modify the HTML.

You can tell this by simply setting a breakpoint at the line that tries to modify the HTML, and notice that it simply doesn't get hit. Another clue is that the window becomes unresponsive.

My recommendation would be to look closer at your algorithm and try to set some limits. console.log statements will be your friend, because they'll help you see what parts of the code are running the most.

Upvotes: 1

Related Questions