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 JavaScript Basics (Retired) Introducing JavaScript Your First JavaScript Program

Harish Yerra
Harish Yerra
10,031 Points

Both alerts are appearing before the h1 text is shown

So this is my code:

alert("Hello from Treehouse");
document.write("<h1>Welcome to Javascript Basics!<h1>");
alert("Thanks for visiting!");

However, once the webpage loads the order of events is as follows:

  1. alert("Hello from Treehouse");
  2. alert("Thanks for visiting!");
  3. document.write("<h1>Welcome to Javascript Basics!<h1>");

However, the teacher says that the program executes in order after each action is completed. So shouldn't it appear in this order:

  1. alert("Hello from Treehouse");
  2. document.write("<h1>Welcome to Javascript Basics!<h1>");
  3. alert("Thanks for visiting!");

1 Answer

Steven Parker
Steven Parker
231,275 Points

:point_right: Nothing written to the document will appear until the JavaScript finishes.

So while the document.write is performed between the alerts, it will not be seen until after the last alert is closed.

Here's a trick you can use to cause the page to appear at the same time as the last alert (and not wait on it closing):

alert("Hello from Treehouse");
document.write("<h1>Welcome to Javascript Basics!<h1>");
setTimeout(function() { alert("Thanks for visiting!"); }, 0);
Harish Yerra
Harish Yerra
10,031 Points

Ahhhh...

That makes sense! Thanks for clarifying :)

Steven Parker
Steven Parker
231,275 Points

I updated my answer with a trick you may find useful. :arrow_heading_up:

Harish Yerra
Harish Yerra
10,031 Points

Cool :)

Thanks for helping me out! So basically, the code above creates a little timeout between the document.write and the alert so that the page updates and then displays an alert.

Is that basically what it does or is the reasoning behind it different?