Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
208,480 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
208,480 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?