Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Waiting for the page to be updated?

Hi all, I'm sure this is a simple one I've missed somewhere along the line, but how would one go about having JS be notified/wait for the change made to an element to be applied before continuing?

I have a very simple example here:

const body = document.getElementsByTagName("body")[0];
const testButton = document.getElementById("testButton");

testButton.addEventListener("click", () => {
  for (let num = 1; num < 6; num++) {
   body.innerHTML += `<p> line ${num} </p>`; 
  }
  console.log("Lines Added");
  alert("Lines Added");
});

So as I understand it, JS runs through this in order when the button is clicked, it adds 5 new p elements to the body element one by one, then calls console.log, and then the alert function.

However what you see in the browser is the log appear in the console, then the alert halts proceedings, and only when you click the alert then the lines are added.

By my understanding this is because the calls are being made by JS in order but take different amounts of time for the browser to complete, so appear to the user in a different order?

I get that usually this isn't a big problem here, but I was just wondering how I would go about ensuring that the console log and alert box wouldn't appear until after the lines were added by the browser and visible to the user? Is there some other kind of event listener i need?

Thanks heaps all! :)

1 Answer

Hi all, so I found a sollution, by giving the update a 1ms delay before proceeding:

const body = document.getElementsByTagName("body")[0];
const testButton = document.getElementById("testButton");

const updateFeedback = () => {
  console.log("Lines Added");
  alert("Lines Added");
}

testButton.addEventListener("click", () => {
  for (let num = 1; num < 6; num++) {
    body.innerHTML += `<p> line ${num} </p>`;
  }
  setTimeout(updateFeedback, 1);                         
});

Any feedback/better solutions appreciated! :)