Search code examples
javascriptfunctionexecution-time

How to update inner HTML before and after a for loop runs


I've built a page which, after submitting form, displays a chart showing the submitted data.

The chart can display up to 10 simulations x 10000 population size x 1000 generations, so after clicking the form the data can take some time to display.

I want to be able to update a div with an id of message with the inner text of 'Loading...' while the for loop doing the calculations is running, then remove the inner text after it has run.

If I console.log("Before") before the for loop, and console.log("After") after the for loop, the messages print out before and after the loop has run.

However, if I put message.innerText = "Loading..." before the loop, and message.innerText = "" after the loop, the "Loading..." message never appears in the HTML.

Here's a (very) highly simplified version of what I've been trying to achieve

I suspect the solution might be using Promises but I can't see a way of applying them to my code. Any suggestions?

const form = document.querySelector("#form")
const message = document.querySelector("#message")

form.addEventListener("submit", e => {
  e.preventDefault()

  console.log("before") // this prints BEFORE for loop ends
  message.innerText = "Loading..." // This is never displayed in html
  for (let i = 0; i < 10000; i++) {
    console.log(i)
  }
  message.innerText = "Loaded" // This is displayed in html
  console.log("after") // this prints AFTER for loop ends
})
<form id="form">
  <button>Submit</button>
</form>

<div id="message"></div>


Solution

  • Try giving the interface a chance

    const form = document.querySelector("#form")
    const message = document.querySelector("#message")
    
    form.addEventListener("submit", e => {
      e.preventDefault()
    
      console.log("before") // this prints BEFORE for loop ends
      message.innerText = "Loading..."
      setTimeout(() => {
        for (let i = 0; i < 1000; i++) console.log(i);
        message.innerText = "Loaded" // This is displayed in html
        console.log("after") // this prints AFTER for loop ends    
      }, 10)
    
      
    })
    <form id="form">
      <button>Submit</button>
    </form>
    
    <div id="message"></div>